Top 50 spring boot interviews : Security

Top 10 Questions on Spring Boot Annotations with Answers

This entry is part 2 of 5 in the series Top 50 Interview Questions and Answers on Spring Boot

Annotations

Question 11. What is the use of the @SpringBootApplication annotation?

The @SpringBootApplication annotation is a meta-annotation in Spring Boot that combines several other critical Spring annotations to simplify the setup and configuration of the Spring Boot application. It marks the main class as the configuration class and enables auto-configuration, which reduces the need for manual setup of beans and dependencies. This annotation signals to the Spring Framework that this is the main class responsible for launching the application.

@SpringBootApplication Annotation Includes

The @SpringBootApplication annotation is a combination of three important annotations

  • @Configuration: Indicates that the class is a source of bean definitions. It replaces the need for separate configuration classes and allows bean definitions in the application to be automatically picked up.
  • @EnableAutoConfiguration: Instructs Spring Boot to automatically configure beans and settings based on the project’s dependencies (e.g., setting up the web server if Spring Web is on the classpath).
  • @ComponentScan: Scans for Spring components (like @Controller@Service@Repository, etc.) in the package of the main class and its sub-packages.

Example

package com.example.mydemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}

Question 12. What is the difference between @RestController and @Controller?

In Spring, both @Controller and @RestController are used to create classes that handle incoming HTTP requests. However, they have distinct purposes:

@Controller

Purpose: Used for traditional web applications where the controller is responsible for handling requests and returning views (HTML, JSP, etc.).
Behavior:
By default, methods within a @Controller class return a view name which is then resolved by a view resolver (like Thymeleaf or JSP) to render an HTML page.
To return data directly (like JSON or XML), you need to explicitly use the @ResponseBody annotation on the method.

Example :

@Controller
public class MyController {

    @GetMapping("/hello")
    public String hello() {
        return "hello"; // Returns the view name "hello"
    }

    @GetMapping("/data")
    @ResponseBody 
    public MyData getData() { 
        // Returns a MyData object as JSON or XML (depending on configuration)
    }
}

}

@RestController

Purpose: Specifically designed for creating RESTful web services that return data directly as JSON, XML, or other formats.

Behavior:

@RestController is a specialized version of @Controller.
It implicitly adds the @ResponseBody annotation to every method within the class.
This means that all methods in a @RestController class will automatically return the object they return as the response body, without the need for the @ResponseBody annotation.

Example :

@RestController
public class MyRestController {

    @GetMapping("/hello")
    public String hello() { 
        // Returns "hello" directly as the response body
    }

    @GetMapping("/data")
    public MyData getData() { 
        // Returns a MyData object directly as JSON or XML
    }
}

}

In Summary:

Use @Controller when you want to build a traditional web application with views.
Use @RestController when you are building a RESTful API that returns data directly.

Question 13. How does the @Autowired annotation work in Spring Boot?

The @Autowired annotation in Spring Boot is used to automatically wire dependencies (beans) into your classes. Here’s how it works:

1. Dependency Injection (DI):

Spring Boot follows the Dependency Injection (DI) principle. This means that instead of your classes directly creating the objects they need, they receive them from an external source (the Spring container).  

2. Role of @Autowired:

The @Autowired annotation tells the Spring container to automatically find and inject a matching bean into the field, constructor, or method parameter where it is used.

3. Matching Beans:
  • Spring searches for a bean that matches the type of the field, constructor parameter, or method parameter.
  • If it finds exactly one matching bean, it automatically injects that bean.
  • If it finds multiple matching beans, it throws a NoUniqueBeanDefinitionException.
  • If it finds no matching beans, it throws a NoSuchBeanDefinitionException.
4. Injection Points:

You can use @Autowired in several places:
Examples Fields:

@Component
public class MyService {

    @Autowired
    private MyRepository repository; 

    // ...
}

Examples – Constructors:

@Component
public class MyService {

    private final MyRepository repository;

    @Autowired
    public MyService(MyRepository repository) {
        this.repository = repository;
    }

    // ...
}

Examples – Methods:

public void doSomething(
        @Autowired MyRepository repository, 
        @Autowired MyOtherService otherService) {
    // ...
}
5. Optional Dependencies:

If you’re not sure whether a bean exists, you can use the @Autowired(required = false) annotation. This will allow the injection to succeed even if no matching bean is found, and the field or parameter will be set to null.


Benefits of @Autowired:
  • Reduced Coupling: Decouples your classes from the creation of their dependencies.
  • Increased Testability: Makes it easier to write unit tests by providing mock objects for dependencies.  
  • Improved Maintainability: Simplifies the process of managing and wiring beans within your application.

By using @Autowired, you can significantly improve the maintainability, testability, and overall design of your Spring Boot applications.

Question 14. What is the purpose of the @Configuration annotation?

The @Configuration annotation in Spring plays a crucial role in defining and managing bean configurations. Here’s a breakdown of its purpose:

1. Bean Definitions:

Declares a Configuration Class: The @Configuration annotation marks a class as a source of bean definitions. This means that methods within this class can be used to define and create beans that will be managed by the Spring container.  

2. Method-Level Bean Definitions:

@Bean Annotation: Within a @Configuration class, methods annotated with @Bean are responsible for creating and returning bean instances.
Bean Name: By default, the bean name is inferred from the method name. You can optionally provide a custom name using the name attribute of the @Bean annotation.  

Example:

@Configuration
public class AppConfig {
@Bean
public MyService myService() {
    return new MyServiceImpl(); 
}

@Bean("customName")
public MyRepository myRepository() {
    return new MyRepositoryImpl(); 
}
}

In this example:

AppConfig is a @Configuration class.
myService() and myRepository() are methods annotated with @Bean, indicating that they will create and return bean instances.
The bean created by myService() will have the default name “myService”.
The bean created by myRepository() will have the name “customName”.

3. Enabling Component Scanning:

The @Configuration annotation can also be used in conjunction with @ComponentScan to enable component scanning within a specific package. This allows Spring to automatically detect and register beans annotated with @Component, @Service, @Repository, etc.
Benefits of @Configuration:

  • Declarative Configuration: Provides a cleaner and more declarative way to define beans compared to XML-based configuration.
  • Maintainability: Improves code maintainability and readability.  
  • Flexibility: Supports various ways to define and configure beans.

By using the @Configuration annotation, you can effectively manage and configure the beans that form the core of your Spring application.

Question 15. What is the difference between @Component, @Service, and @Repository?

In Spring, @Component, @Service, and @Repository are all stereotypes annotations that mark classes as beans for the Spring container to manage. While they all have the same core functionality, they provide semantic meaning and improve code organization.

@Component:

Purpose: The most general annotation. It simply indicates that a class is a Spring component and should be managed by the Spring container.
Usage: Can be used for any class that you want to be a Spring bean, regardless of its specific role.

Example:

@Component
public class MyGeneralComponent {
// …
}
@Service:

Purpose: Specifically designed for business logic classes (services).
Usage: Marks classes that contain business logic, such as data processing, calculations, and interactions with other services.
Provides Semantic Meaning: Clearly indicates the purpose of the class within your application.

Example:
@Service
public class MyBusinessService {
// …
}
@Repository:

Purpose: Specifically designed for data access objects (DAOs).
Usage: Marks classes that interact with databases or other data sources.
Exception Handling: Often used in conjunction with Spring’s @Transactional annotation for declarative transaction management.
Provides Semantic Meaning: Clearly indicates the role of the class in data access.

Example:
@Repository
public class MyDataRepository {
// …
}

In Summary:

All three annotations mark classes as Spring beans.
@Component is the most general and can be used for any class.
@Service is specifically for business logic classes.
@Repository is specifically for data access objects.

Question 16. What is @EnableAutoConfiguration, and how is it used?

@EnableAutoConfiguration is a core annotation in Spring Boot that simplifies application configuration by automatically setting up beans and services based on the libraries available in your project. This tutorial will guide you through its purpose, usage, and customization.

What is @EnableAutoConfiguration?

@EnableAutoConfiguration scans the classpath for dependencies and configures the application accordingly.

For example:

If spring-boot-starter-web is included, it configures a web server (like Tomcat) and Spring MVC.

If spring-boot-starter-data-jpa is present, it configures a DataSource and JPA-related beans.

This annotation is included implicitly in @SpringBootApplication, which is a combination of:

  • @Configuration
  • @EnableAutoConfiguration
  • @ComponentScan

How It Works

Spring Boot scans the classpath for JAR files and dependencies.

Based on the libraries found, it configures the necessary beans and settings.

This reduces the need for manual configuration and boilerplate code.

Using @EnableAutoConfiguration

While @EnableAutoConfiguration is typically included via @SpringBootApplication, you can use it explicitly if needed.

Example 1: Explicit Usage

@Configuration
@EnableAutoConfiguration
public class MyAppConfig {
public static void main(String[] args) {
SpringApplication.run(MyAppConfig.class, args);
}
}

Customizing Auto-Configuration

You can exclude specific auto-configuration classes if they interfere with your custom setup or are unnecessary for your application.

Example: Excluding a Single Auto-Configuration

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

Example: Excluding Multiple Auto-Configurations

@EnableAutoConfiguration(exclude = {
DataSourceAutoConfiguration.class,
HibernateJpaAutoConfiguration.class
})
public class MyAppConfig {
public static void main(String[] args) {
SpringApplication.run(MyAppConfig.class, args);
}
}
Benefits of @EnableAutoConfiguration

Reduced Boilerplate Code: Eliminates the need for extensive manual configuration.

Context-Aware: Automatically adapts to the dependencies in your project.

Faster Development: Simplifies setup, especially for microservices.

Note :

Unexpected Behaviors: Over-reliance on auto-configuration may lead to unintended results if you’re unaware of what is being configured.

Customization Required: For specific needs, you might need to disable certain auto-configurations and define custom settings.

Conclusion

@EnableAutoConfiguration is a powerful feature of Spring Boot that enhances productivity by automating configuration based on the application’s needs. By understanding its usage and customization options, you can harness its full potential while maintaining control over your application’s behavior.

Question 17. What is the @Bean annotation in Spring Boot?

The @Bean annotation in Spring Boot is used to define a bean (an object managed by the Spring container) explicitly. It is typically placed on a method within a configuration class annotated with @Configuration.

What is the Purpose of @Bean?

The @Bean annotation allows you to define and configure beans programmatically. These beans are then managed by the Spring IOC(Inversion of Control) container, making them available for dependency injection throughout your application.

How to Use @Bean?

Create a method in a class annotated with @Configuration.

Annotate the method with @Bean.

Return the object you want to register as a bean.

Example 1: Defining a Simple Bean

@Configuration
public class AppConfig {
@Bean
public MyService myService() {
    return new MyService();
}
}
class MyService {
public void performTask() {
System.out.println("Task performed!");
}
}

Usage

@RestController
public class MyController {
private final MyService myService;

public MyController(MyService myService) {
    this.myService = myService;
}

@GetMapping("/task")
public String performTask() {
    myService.performTask();
    return "Task completed!";
}
}
Benefits
  • Explicit Control: Gives you full control over the bean’s creation and configuration.
  • Custom Initialization: Allows you to initialize beans with specific parameters or logic.
  • Integration: Useful for integrating third-party libraries or legacy code that cannot be annotated directly.
Conclusion

The @Bean annotation is a powerful tool for defining and managing beans explicitly in Spring Boot. It complements Spring’s automatic component scanning and provides flexibility for custom configurations and integrations.

Question 18. How does the @RequestMapping annotation work?

The @RequestMapping annotation in Spring Boot is tell your application which web address (URL) should trigger a specific piece of your code (a method in a controller). It’s the core of routing web requests to the right place.  

For example –

Lets Imagine a post office:how it works?

Each house has an address: This is like the URL of your web page (e.g., /products, /users/profile).
The postman delivers mail to the correct address: @RequestMapping is like the postman. It reads the web address in the request and finds the matching method in your code.  

How it works in your code:

You create a “controller” class: This class handles web requests. You mark it with @Controller or @RestController (if it’s a REST API).  

You add @RequestMapping to methods inside the controller: This tells Spring Boot which URL should call that method.  

Example-

@RestController // This is a controller for a REST API
public class MyController {
@RequestMapping("/hello") // This method is called when someone goes to /hello
public String sayHello() {
    return "Hello, world!";
}

@RequestMapping("/products/{id}") // This method is called when someone goes to /products/1, /products/2, etc.
public String getProduct(@PathVariable int id) {
    return "Product " + id;
}
}
Key things @RequestMapping can do:
  • Match different URLs: You can have different @RequestMapping annotations for /products, /users, /about, etc.
  • Match different request types: You can specify if a method should be called only for GET requests (when you open a page in your browser), POST requests (when you submit a form), and so on.
  • Take data from the URL: Like in the /products/{id} example, you can extract parts of the URL as variables to use in your code.

Simplified versions:

Because specifying the request type (GET, POST, etc.) is so common, Spring Boot provides simpler annotations:

@GetMapping(“/hello”) is the same as @RequestMapping(value=”/hello”, method=RequestMethod.GET)
@PostMapping(“/submit”) is the same as @RequestMapping(value=”/submit”, method=RequestMethod.POST)

Conclusion:


@RequestMapping is how Spring Boot knows which method in your code should handle a specific web request, based on the URL and the type of request. It’s like a traffic controller for your web application.

Question 19. What is the use of @PathVariable and @RequestParam?

@PathVariable and @RequestParam are both Spring annotations used to extract data from incoming HTTP requests, but they extract data from different parts of the request:

@PathVariable:

Extracts data from the URL path itself.  
Used for dynamic segments within the URL.  
Often used for identifying specific resources (like an ID).  
Example:

Example :

@GetMapping("/products/{productId}")
public String getProduct(@PathVariable("productId") Long productId) {
// … use productId to retrieve the product …
return "productView";
}

In this example:

If a user visits /products/123, the value 123 will be extracted and assigned to the productId variable.

@PathVariable

@PathVariable(“productId”) tells Spring to extract the value from the path segment named productId. If the variable name in the method matches the path segment name, you can simplify it to @PathVariable Long productId.

Use cases for @PathVariable:

Retrieving a specific resource by ID (e.g., /users/123, /products/456).
Creating RESTful APIs where resources are identified by their path.
Building hierarchical URLs (e.g., /categories/electronics/products/123).
@RequestParam:

Extracts data from query parameters in the URL.  
Used for optional or required parameters passed in the URL after a question mark (?).
Often used for filtering, sorting, or pagination.  
Example:

Example
@GetMapping("/products")
public String getProducts(@RequestParam(value = "category", required = false) String category,
@RequestParam(value = "page", defaultValue = "1") int page) {
// … use category and page to filter and display products …
return "productsList";
}

In this example:

If a user visits /products?category=electronics&page=2, the value “electronics” will be assigned to the category variable, and the value 2 will be assigned to the page variable.
@RequestParam(“category”) tells Spring to extract the value of the category query parameter.
required = false makes the category parameter optional. If it’s not present in the URL, category will be null.
defaultValue = “1” provides a default value for the page parameter if it’s not present in the URL.
Use cases for @RequestParam:

Searching or filtering data (e.g., /products?search=keyword, /users?country=US).
Pagination (e.g., /products?page=2&size=10).
Passing optional parameters to a request.  


Key Differences Summarized:

Difference between @PathVariable and @RequestParam

Feature@PathVariable@RequestParam
Data SourceURL path segmentsQuery parameters in the URL (after the ?)
UsageIdentifying specific resourcesFiltering, sorting, pagination, optional parameters
Example URL/products/123/products?category=electronics&page=2
Required/OptionalGenerally required as it’s part of the URL structureCan be made optional using required = false
Default ValueNot applicable (part of the URL structure)Can have a default value using defaultValue
@PathVariable Vs @RequestParam
Conclusion:

use @PathVariable when the data is part of the URL’s structure and identifies a specific resource. Use @RequestParam when the data is passed as optional or required parameters to modify the request.

Question 20. What is the @Profile annotation in Spring Boot?

The @Profile annotation in Spring Boot provides a way to conditionally enable or disable certain beans (components, services, configurations) based on the active environment. It allows you to customize your application’s behavior for different deployment scenarios, such as development, testing, staging, and production.  

Think of it like having different sets of configurations for different situations. You wouldn’t want to use your production database credentials during development, and you might want to enable certain debugging tools only in a development environment. @Profile helps you manage these differences.

How it works:

Annotate beans with @Profile: You apply the @Profile annotation to classes annotated with @Component, @Service, @Configuration, or @Bean. The annotation takes one or more profile names as its value.

Example

Profile= DEV

@Configuration
@Profile("dev") // This configuration is only active in the "dev" profile
public class DevConfig {
@Bean
public DataSource dataSource() {
// Configure a development database
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.build();
}
}

Profile=PROD

@Configuration
@Profile("prod") // This configuration is only active in the "prod" profile
public class ProdConfig {
@Bean
public DataSource dataSource() {
// Configure a production database
DriverManagerDataSource dataSource = new DriverManagerDataSource();
// … set production database properties …
return dataSource;
}
}

Activate profiles: You can activate profiles in several ways:

spring.profiles.active property: This is the most common way. You can set this property in your application.properties or application.yml file, as a command-line argument, or as an environment variable.

application.properties: spring.profiles.active=dev
Command-line: java -jar myapp.jar --spring.profiles.active=prod
Environment variable: SPRING_PROFILES_ACTIVE=staging

Programmatically: You can set active profiles programmatically using the SpringApplicationBuilder:

Example

new SpringApplicationBuilder(MyApplication.class)
.profiles("test")
.run(args);


Conditional bean creation: When Spring Boot starts, it checks the active profiles and only creates beans that are annotated with matching profiles. In the example above, if the dev profile is active, the DevConfig bean will be created, and if the prod profile is active, the ProdConfig bean will be created.

Example scenarios:

Different databases: Use different database configurations for development (e.g., in-memory H2 database) and production (e.g., PostgreSQL or MySQL).
Mock services for testing: Create mock implementations of services for unit tests.
Feature toggles: Enable or disable certain features based on the environment.  
Logging configurations: Use different logging levels for development and production.
Default Profile:

If no profiles are explicitly activated, Spring Boot uses the default profile. You can define beans that are active by default by either not using the @Profile annotation at all, or using @Profile(“default”).

Multiple Profiles:

You can specify multiple profiles in the @Profile annotation or the spring.profiles.active property:

@Profile({"dev", "debug"})
spring.profiles.active=dev,debug

In this case, the bean will be active if any of the specified profiles are active.

Conclusion:

@Profile is a powerful tool for managing environment-specific configurations in your Spring Boot applications. It helps you keep your code clean, organized, and adaptable to different deployment scenarios.

To Read more spring boot annotation Here

Series Navigation<< Top 10 Questions on Spring Boot Basics with AnswersTop 10 Questions on Spring Boot Data Handling with Answers >>

Leave a Reply

Your email address will not be published. Required fields are marked *