Codementor Events

Spring Boot Annotations That a Developer Should Know

Published Jun 11, 2021
Spring Boot Annotations That a Developer Should Know

Spring Boot Annotations are a type of metadata that offers information about a program that is not contained within it. They have no direct impact on the code that they annotate.

The convention over configuration principle is used instead of XML in Spring Boot Annotations. Since Java 5.0, the Java programming language has supported annotations. Annotations were quickly adopted by leading Java frameworks, and the Spring Framework began using them in version 2.5. Annotations include a lot of context in their declaration due to the manner in which they are defined.

Spring Boot Annotations

@Configuration
This annotation is applied to bean-defining classes. @Configuration is a Java class that acts as an analog to an XML configuration file. A Java class marked with the @Configuration annotation is a configuration in and of itself, including methods for instantiating and configuring dependencies.

@Bean
At the method level, this annotation is used. The @Bean annotation is used in conjunction with the @Configuration annotation to build Spring beans. @Configuration will include methods for creating and configuring dependencies. @Bean will be appended to such methods. The method with this annotation acts as a bean ID, creating and returning the actual bean.

Example:

@Configuration
public class Sample{
  @Bean
  public Element element(){
    return new Element(name());
  }
  @Bean
  public Name name(){
    return new Name();
  }
}

@Autowired
Fields, setter methods, and constructors all have this annotation. The @Autowired annotation implicitly injects object dependencies. Spring will automatically assign the fields with the supplied values when you use @Autowired on fields and pass the values for the fields using the property name. @Autowired can also be used on private properties, as demonstrated below.

public class Sample {
    @Autowired                               
    private Element element;                   
    private Name name;
}

When you use @Autowired on setter methods, Spring attempts to autowire the method by Type. You're telling Spring that it should start this property with a setter method where you can put your custom code, just as you had to do with any other property.

public class Sample {                                                                                         
    private Element element;
    @Autowired                                                                                                      
    public void setElement(Element element) {
     this.element=element;
    }
}

Constructor Injection occurs while an object is created if we use @Autowired on a constructor. When used as a bean, it signals the constructor to autowire. One thing to keep in mind is that each bean class can only have one constructor with the @Autowired annotation.

@Required
On bean setter methods, this annotation is used. Consider a situation in which you must enforce a mandatory property. The @Required annotation indicates that the required attribute must be filled in at configuration time for the affected bean. Otherwise, a BeanInitializationException exception is thrown.

@Lazy
On component classes, this annotation is used. At startup, all autowired dependencies are automatically built and configured. However, you can use the @Lazy annotation over the class to lazy initialise a bean. This indicates that the bean will only be produced and initialised when it is requested for the first time.

@Value
At the field, constructor parameter, and method parameter levels, this annotation is used. The @Value annotation specifies a default value expression for a field or parameter that will be used to initialise the property. You can use the @Value annotation to inject values from a property file into a bean's attribute, much as you can with the @Autowired annotation when Spring loads your application context. #{...} and ${...} placeholders are both supported.

@Qualifier
Together with the @Autowired annotation, this annotation is used. @Qualifier can be used when you require extra control over the dependency injection process. Individual constructor arguments or method parameters can have @Qualifier provided. When you generate multiple beans of the same type and wish to wire only one of them with a property, this annotation is used to minimise confusion.

Example

@Component
public class Bean1 implements SampleInterface {
  //
}
@Component
public class Bean2 implements SampleInterface {
  //
}
@Component
public class Bean3 implements SampleInterface {
  //
}

Here, three beans Bean1, Bean2 and Bean3 have implemented the interface SampleInterface.
Spring will not know which of the two implementations to inject if another bean autowires this interface.
The @Qualifier annotation is one way to solve this problem.

@Component
public class SampleBean {
  @Autowired
  @Qualifier("bean2")
  private SampleInterface dependency;
    /*
        Code
    */ 
}

@Component
This annotation is used to specify a Spring component on a class. The @Component annotation designates a Java class as a bean, or component, in order for Spring's component-scanning mechanism to add it to the application context.

@Controller
The @Controller annotation denotes that a class is a Spring controller. This annotation can be used to identify Spring MVC or Spring WebFlux controllers.

@Repository
This annotation is applied to Java classes that have direct database access. Any class that serves as a repository or Data Access Object can use the @Repository annotation as a marker.

An automatic translation option is included in this annotation. When an exception happens in the @Repository, the exception has a handler, thus there is no need to add a try catch block.

@Service
This is an annotation that is applied to a class. A Java class with the @Service annotation performs a service, such as executing business logic, performing calculations, or calling external APIs. This is a customised version of the @Component annotation designed for use in the service layer.

** @EnableAutoConfiguration**
The main application class is frequently annotated with this annotation. A base "search package" is implicitly defined by the @EnableAutoConfiguration annotation. Spring Boot will start adding beans based on classpath settings, other beans, and various property settings if this annotation is present.

@SpringBootApplication
When creating a Spring Boot project, this annotation is applied to the application class. The class with the @SpringBootApplication annotation must be retained in the base package. The component scan is the only thing the @SpringBootApplication does. However, it will only scan its sub-packages. The @SpringBootApplication annotation is useful since it adds all of the following:

  • @EnableAutoConfiguration
  • @ComponentScan
  • @Configuration

@Controller
This annotation is applied to Java classes in your programme that serve as controllers. The @Controller annotation allows component classes in the classpath to be auto-detected and bean declarations for them to be auto-registered. You can add component scanning to your settings to enable autodetection of such annotated controllers. The @Controller annotation on a Java class allows it to handle multiple request mappings. Spring MVC and Spring WebFlux both support this annotation.

@CrossOrigin
This annotation is used to facilitate cross origin requests at both the class and method level. The host that serves JavaScript is frequently distinct from the server that serves data. Cross Origin Resource Sharing (CORS) allows cross-domain connectivity in this instance.

Simply add the @CrossOrigin annotation to enable this connection. The @CrossOrigin annotation permits all origins, all headers, all HTTP methods defined in the @RequestMapping annotation, and a maximum age of 30 minutes by default. By changing the values of the corresponding attribute values, you can tailor the behaviour.

@CrossOrigin(maxAge = 1400)
@RestController
@RequestMapping("/address")
public class AddressController {
@CrossOrigin(origins = "URL_NAME")
@RequestMapping("/message")
  public Message getMessage() {
      /*
        ...
      */
    }
 
@RequestMapping("/state")
    public Note getState() {
        /*
        ...
        */
    }
}

Both the getMessage() and getState() methods will have a maxAge of 1400 seconds in this example. Also, getMessage() only accepts cross-origin queries from 'URL_NAME', whereas getState() accepts requests from any host.

@CookieValue
At the method parameter level, this annotation is used. The @CookieValue is used in the argument of the request mapping method. For a particular cookie name, the HTTP cookie is tied to the @CookieValue argument. This annotation is used in the @RequestMapping annotation method.

Example

@RequestMapping("/valueCookie")
  public void getValueCookie(@CookieValue "SESSIONID" String Cookie){
}

@Transactional
This annotation goes before an interface definition, an interface method, a class definition, or a class's public method. The presence of @Transactional alone does not trigger transactional behaviour. @Transactional is merely metadata that some runtime infrastructure can consume. The metadata is used by this architecture to configure the relevant beans with transactional behaviour.

@RequestAttribute
The request attribute is bound to a handler method parameter using this annotation. Spring gets the value of the named attributes and uses it to populate the @RequestAttribute parameter. The @RequestParam annotation is used to bind parameter values from the query string, whereas the @RequestAttribute is used to access the server-side-populated objects.

@RequestBody
Request handler method arguments are annotated with this annotation. A method argument should be tied to the value of the HTTP request body, according to the @RequestBody annotation. The HttpMessageConveter is in charge of translating HTTP request messages into objects.

@RequestHeader
Request handler method arguments are annotated with this annotation. To map a controller parameter to a request header value, use the @RequestHeader annotation. When Spring maps the request, @RequestHeader compares the header name to the annotation name and binds the value to the handler method parameter. This annotation aids in the retrieval of header information within the controller class.

@RequestParam
Request handler method arguments are annotated with this annotation. The parameters are sometimes included in the request URL, which is most common in GET queries. You can use the @RequestParam annotation in conjunction with the @RequestMapping annotation to obtain the URL parameter and map it to the method argument in that scenario.

@ResponseBody
Request handler methods are annotated with this annotation. The @ResponseBody annotation is similar to the @RequestBody annotation in that it specifies the body of the response. The @ResponseBody annotation specifies that the response body should contain the result type in whatever format you specify, such as JSON or XML. The HttpMessageConveter is used by Spring to convert the returned object into a response body.

Conclusion

Spring Boot has simplified the process of creating Spring applications for Java developers. You should be familiar with the basic Spring boot annotations if you're a Java enthusiast or professional. In this article we have covered all the basic annotations that one should know.

Discover and read more posts from Arjunk
get started
post commentsBe the first to share your opinion
Show more replies