Wednesday, May 1, 2024

Top 20 Spring Framework Annotations Java Developers Should Know

Hello guys, annotations are quite important when working in modern Java application as almost all frameworks and libraries nowadays use annotations, including Spring Framework. There was time when we need to remember classes and methods to make effective use of JDK or any open source library but now we also need to remember annotations. For example, to use JUnit you must know about annotations like @Test, @BeforeEach, @AfterEach, @Disabled and so on. Similarly for Spring framework you need to know annotations like @Configuration, @Bean, @Component, @Service, @Value, @Autowired, @Repository, @Qualifier, @Required and more. 

In the past, I have shared important Spring Boot annotations and Spring MVC and REST annotations and today, I am going to share key annotation for Spring core framework.  I will list down all important annotations, explain you what they do and also give you a code example so that you can understand when to use them. 

So what are we waiting for, let's start this annotation journey with most essential Spring annotations for Java development. 


20 Essential Spring Framework Annotations for Java Developers

Here are some of the important annotations form Spring Framework. This list includes annotations from Spring core e.g. container and DI support, Spring MVC, Spring REST, Spring Security, and Spring JDBC. 

Top 20 Spring Framework Annotations Java Developers Should Know


1. @Component

This Spring annotation Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

Other class-level annotations may be considered as identifying a component as well, typically a special kind of component: e.g. the @Repository annotation or AspectJ's @Aspect annotation.

Here is an example of @Component annotation in Sping:

import org.springframework.stereotype.Component;

@Component
public class SpringComponnet{
    // Class implementation
}
In this example, the SpringComponent class is annotated with @Component, indicating that it's a Spring-managed component. Spring will automatically detect this class during component scanning and manage its lifecycle, allowing it to be used within the application context.

2. @Bean

This Spring annotation Indicates that a method produces a bean to be managed by the Spring container. The names and semantics of the attributes to this annotation are intentionally similar to those of the element in the Spring XML schema. 

For example:

@Bean
public MyBean myBean() {
// instantiate and configure MyBean obj
  return obj;
}
This method indicate that it will return a Spring bean with type MyBean.

3. @AutoWired

The @Autowired Spring annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like the @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.

Here is an example of how to use @Autowired annotation to automatically inject dependency at runtime

import org.apache.kafka.clients.consumer.Consumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RdsKafkaConsumer {

    private Consumer<String, String> kafkaConsumer;

    @Autowired
    public RdsKafkaConsumer(Consumer<String, String> kafkaConsumer) {
        this.kafkaConsumer = kafkaConsumer;
    }

    // Other methods using kafkaConsumer
}

In this example, RdsKafkaConsumer is a Spring-managed component, and it relies on a Kafka Consumer instance as a dependency. I have used @Autowired annotation in its constructor to enable the injection of the Kafka Consumer bean, streamlining the process of consuming Kafka messages without the need for manual instantiation and configuration of the Kafka consumer instance.


4. @Qualifier

The @Qualifier annotation from Spring can actually help @Autowired annotation in case of ambiguity. Suppose you have to create more than one bean of the same type and want to wire only one of them with a property. 

In such cases, you can use the @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired.

Here is an example of using @Qualifier annotation in Spring. In this example we have a class NotificationService which depends upon MessagingService to send notifications, but there are multiple implementation of MessagingService is available like EmailService or SMSService. 

I have used @Qualifier("emailService") to specify that we want the EmailService implementation to be injected into NotificationService? make sense?




5. @PostConstruct and @PreDestroy

These Spring annotations are annotation form of init() and destroy() method attribute of bean tag in Spring configuration XML.

The method annotated with @PostConstruct is called once the bean properties are initialized and the method annotated with @PreDestroy is called before the spring container destroys the instance of a bean. 


6. @Configuration

This Spring annotation indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime, for example:

@Configuration
public class AppConfig {

@Bean
public MyBean myBean() {
// instantiate, configure and return bean ...
}
}


7. @Controller

This is a Spring MVC annotation. It indicates that an annotated class is a "Controller" (e.g. a web controller).This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the RequestMapping annotation. 

From Spring 3.0, the @Controller mechanism also allows you to create RESTful Web sites and applications, through the @PathVariable annotation and other features. 

Spring heavily uses Open closed design principle to prevent some of the core methods to be overridden.  

You can read more about these design decision at Expert Spring Web MVC and Web Flow by Seth Ladd and others;


8. @RestController

This is another Spring MVC annotation added on Spring 4.0 for easier development of RESTful Web Services using Spring framework. 

The @RestController is a convenience annotation that is itself annotated with @Controller and @ResponseBody.  Which means instead of annotating your class with both @Controller and @ResponseBody, you can just annotate with @RestController and it will have same effect. 

Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default.


9. @RequestParam

This Spring MVC Annotation indicates that a method parameter should be bound to a web request parameter. This annotation is supported for annotated handler methods in Servlet and Portlet environments.

If the method parameter type is Map and a request parameter name is specified, then the request parameter value is converted to a Map assuming an appropriate conversion strategy is available.

10. @RequestBody

This is another Spring MVC annotation which was added on Spring 3.0 version. This annotation indicates that a method parameter should be bound to the body of the web request. 

The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request. 

Optionally, automatic validation can be applied by annotating the argument with @Valid. Supported for annotated handler methods in Servlet environments.


11. @ResponseBody

This is another Spring MVC annotation which is similar to @RequestBody. If you annotate a method in controller with @ResponseBody the Spring MVC will try to convert its return value and write it to the http response directly. 

Just like when you annotate a methods parameter with @RequestBody, spring will try to convert the content of the incoming request body to your parameter object on the fly.

Both @RequestBody and @ResponseBody annotations of the spring MVC framework can be used in a controller to implement smart object serialization and deserialization. 

They help you avoid boilerplate code by extracting the logic of message conversion and making it an aspect. Other than that they help you support multiple formats for a single REST resource without duplication of code.


12. @RequestMapping

This is one of the important annotation of Spring MVC framework, which allows you to map HTTP requests onto specific handler classes and/or handler methods. It also provides a consistent style between Servlet and Portlet environments, with the semantics adapting to the concrete environment. I have shared 10 examples of @ReqestMapping annotation here. 


13. @EnableWebMVC

This is another useful Spring MVC annotation which was added on Spring 3.1 version. Adding this annotation to an @Configuration class imports the Spring MVC configuration from WebMvcConfigurationSupport, like.:

@Configuration
@EnableWebMvc
@ComponentScan(basePackageClasses = { MyConfiguration.class })
public class MyWebConfiguration {

}

The new @EnableWebMVC annotation can do a lot of useful things, especially in the case of RESTful Web Services. It can detect the existence of Jackson and JAXB 2 library on the classpath and automatically creates and registers default JSON and XML converters. 


14. @PathVariable

This is another useful Spring MVC annotation which was added on Spring 3.0 version. It indicates that a method parameter should be bound to a URI template variable. In simple word, @PathVariable annotation is use to retrieve some placeholder from the URI. 

15. @Transactional

This annotation is used to provide transaction support. You can use this to enable for programmatic and declarative transaction in Spring. 

16. @Secured

This is a Spring security annotation which is used for method level security. 

17. @RolesAllowed

This is another Spring security annotation which is used for method level security. 

18. @ResponseStatus

This annotation is used while developing RESTful web services using Spring framework to override the HTTP response code sent my Spring. For example, when you create a resource using POST method, standard response from Spring is 200 OK, but by using @ResponseStatus annotation you can send 201 Created, which is more descriptive and better response code to indicate successful creation of a resource in server. 

19. @Value

The @Value annotation is used to inject values from property files and environment variables into spring managed benas, fields and managed parameters. 

20. @WebMvcTest and @DataJpaTest

Both @WebMvcTest and @DataJpaTest annotations are provided by Spring Boot Testing framework to test the specific layer of Spring application. For example, @WebMvcTest can be used to test the web layer, particularly the controllers. 

When we use @WebMvcTest annotation, spring boot will automatic configure all @Controller, @ControllerAdvice, @JsonComponent, Converter, GenericConverter, Filter, WebMvcConfigurer, and HandlerMethodArgumentResolver beans.

Similarly, @DataJPATest annotation is used to test repository layer of spring application and when you use this annotation, Spring boot will auto-configure an in memory database for you. 

That's all about essential annotations for Spring, Spring MVC and Spring Security. This is the bare minimum list of annotations every Java developer should know and aware of. If you have any questions about any of these annotations feel free to ask in comments. 

Other Spring related articles you may like to explore this blog
  • 23 Spring MVC Interview questions for 2 to 3 years experienced (list)
  • What is the use of DispatcherServlet in Spring MVC? (answer)
  • 20+ Spring and REST Interview Questions (questions)
  • 3 ways to learn Spring Framework better (article
  • 25 Spring Security Interview Questions (spring security questions)
  • How to enable Spring security in Java application? (answer)
  • 13 Spring Actuator interview questions (spring actuator questions)
  • Does Spring certification help in Job and Career? (article)
  • Top 5 Spring Certification Mock Exams (list)
  • Difference between @Autowired and @Injection annotations in Spring? (answer)
  • 20 Spring Boot Testing Interview questions (Spring boot questions)
  • 10 Spring Annotation Java Developers Should Know (annotations)
  • Top 5 Spring Boot Features for Java Developers (features)

Thanks for reading this article. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment and I'll try to answer it as soon as possible.

2 comments :

Anonymous said...

I want to use Kafka with Spring Boot as I have to publish messages to a Kafka queue? How can I do that?

Anonymous said...

Hmmm seems like you are stuck

Post a Comment