Hi buddies welcome to our blog ,crtr4u.com and today we are going to understand most important annotation in Spring Boot , if you go for any Java Developer interviews nowadays , Almost every interviewer in interviews asking questions on Annotation in Spring Boot.
Important Annotation in Spring Boot for Interviews
Spring Boot annotations are a type of metadata that provide instructions and information about your Spring Boot application. They simplify development by reducing the amount of boilerplate configuration code you need to write. Here’s a breakdown of some important Spring Boot annotations:
@SpringBootApplication
@SpringBootApplication: This is the most important annotation in Spring Boot. It’s a powerful combination of three other annotations:
- @EnableAutoConfiguration : This annotation Enables automatic configuration of beans based on the libraries you have on your class path. Spring Boot scans for specific libraries and automatically configures beans for things like Data Source, JPA, and Spring MVC.
- @ComponentScan : This annotation Tells Spring Boot to scan a specific base package and its sub-packages for components,(here components means classes annotated with annotations such as @Component,@Controller, @Service etc.). This allows Spring to find and manage your beans.
- @Configuration : Marks a class as a Java Bean configuration class and This class can contain methods annotated with @Bean to define explicit bean configurations.
@Bean
@Bean annotation : This annotation is used on a method within a class annotated with @Configuration annotation to explicitly define a bean. The method returns an instance of the bean that will be managed by the Spring IoC container.
@SpringBootConfiguration
@SpringBootConfiguration : This annotation is a cousin to @Configuration. It essentially serves the same purpose but is specifically designed for Spring Boot applications. It can be used interchangeably with @Configuration in most cases, but using @SpringBootConfiguration allows Spring Boot to automatically discover your configuration class.
@PropertySource
This annotation allows you to specify externalized configuration properties files. You can define properties in a .properties or .yml file and use this annotation to load them into your Spring Boot application. This promotes cleaner code and easier management of configuration settings.
@ConditionalOnClass and @ConditionalOnMissingClass
These annotations are part of Spring’s conditional configuration feature. They allow you to configure beans conditionally based on the presence or absence of specific classes on the classpath. This is useful for enabling or disabling features based on dependencies.
@ConditionalOnBean and @ConditionalOnMissingBean
@ConditionalOnBean and @ConditionalOnMissingBean : Similar to the class-based conditionals, these annotations allow you to configure beans conditionally based on the presence or absence of other beans in the Spring context. This provides more granular control over bean creation.
@Profile
This annotation allows you to define different configuration profiles for your Spring Boot application. You can activate a specific profile by setting an environment variable or using a command-line argument. This is useful for configuring your application differently for development, testing, and production environments.
@RestController
This annotation is a combination of @Controller and @ResponseBody. It’s commonly used for building RESTful APIs in Spring Boot applications. Classes annotated with @RestController automatically return response data in the body of the HTTP response.
@Autowired
This annotation is not specific to Spring Boot, but it’s heavily used in Spring applications. It tells Spring to automatically inject dependencies (other beans) into a bean. This simplifies bean wiring and promotes loose coupling in your code.
@SpringBootApplication(scanBasePackages = {“…”)})
While @SpringBootApplication scans by default, you can use scanBasePackages to explicitly specify which packages to scan for components. This is useful for complex projects with multiple modules or to isolate configurations.
@Qualifier
This annotation helps differentiate between multiple beans of the same type. By using @Qualifier
with an argument alongside @Autowired, you can tell Spring which specific bean to inject.
@Primary
If you have multiple beans implementing the same interface, @Primary marks the preferred one for autowiring. This helps avoid ambiguity when Spring tries to decide which bean to inject.
@EventListener
This annotation allows you to define methods that listen for specific application events. These events can be Spring Framework events or custom events you define. This enables reactive programming and responding to application state changes.
@ControllerAdvice
This annotation marks a controller class that provides centralized exception handling advice. You can define methods annotated with @ExceptionHandler to handle specific exceptions thrown by your application controllers.
@FeignClient
This annotation is used for building declarative Feign clients for interacting with microservices. It simplifies service interactions by hiding the underlying HTTP details.
@WebMvcConfigurer
This interface provides methods for customizing Spring MVC behavior. You can override methods to configure things like message converters, formatters, and interceptors for web requests.
@EnableScheduling
This annotation enables Spring’s task scheduling functionality. You can use @Scheduled on methods within a bean to schedule their execution at specific intervals or fixed times.
@Async
This annotation marks a method as asynchronous. When called, the method will be executed by a separate thread from the caller’s thread pool. This is useful for long-running tasks that shouldn’t block the main thread.
@Repository
This annotation marks a data access layer class (like a JPA repository). It provides basic CRUD operations (Create, Read, Update, Delete) for interacting with your database.
@RequestMapping
@RequestMapping annotation Maps a specific URL path or pattern to a controller method. Handles incoming HTTP requests.
@PathVariable
Extracts a value from a URI template variable and injects it as a method argument. Useful for capturing dynamic parts of the URL.
@RequestBody
Annotates a method argument to indicate it receives the request body as a whole object. Often used with JSON or XML data.
Security Annotations:
@EnableWebSecurity: Enables Spring Security configuration for your application.
@PreAuthorize: Defines authorization checks before a method execution.
@Secured: Secures a method by requiring specific roles.
Testing Annotations:
@SpringBootTest: Loads the entire Spring Boot application context for integration tests.
@MockBean: Creates a mock bean for unit testing, replacing the real implementation.
@SpringRunner: (deprecated in favour of @SpringBootTest) Used with JUnit for Spring Boot tests.
WebSockets Annotations:
@EnableWebSocket: Enables WebSocket support for your application.
@Controller: Can be used with WebSocket controllers for handling messages.
@OnMessage: Annotates methods to handle incoming WebSocket messages.
Caching Annotations:
@EnableCaching: Enables caching functionality for your application.
@Cacheable: Annotates methods to cache their return values.
@CachePut: Annotates methods to update cache entries after method execution.
Profile-Specific Annotations:
@Profile(“dev”): Annotates configurations specific to the development environment.
@ConditionalOnProperty: Enables configuration based on presence/value of a system property.
@Value(“${prop.name}”): Injects property values from configuration files based on active profile.
Remember, exploring official Spring Boot documentation is a great resource for in-depth information on these annotations and more: https://docs.spring.io/spring-boot/docs/current/reference/html/documentation.html.
Happy Learning…