With newer iterations of the technology, Java5.0 began to support annotations. As the leading framework in Java, Spring has gradually abandoned XML configuration and used annotations to control the Spring framework since the 2.5 update.

Spring has so many annotations that you may not be able to use them for many years. Here’s a summary of the seven most commonly used annotations by type. A complete PDF version of the Java Interview handbook has been organized into a document

I. Core notes

@Required

This annotation is used on setter methods of beans. Said this attribute is required, must be in the configuration phase injection, otherwise you will be thrown BeanInitializationExcepion.

@Autowired

This annotation is used to explicitly declare dependencies on the bean’s field, setter methods, and constructors. Autowiring is based on type.

When you use this annotation on a field and use a property to pass a value, Spring automatically assigns the value to the field. You can also use this annotation for private attributes (not recommended), as follows.

@Component
public class User {
    @Autowired                               
    private Address address;                   
}
Copy the code

The most common use is to use this annotation on a settter so that you can add custom code to setter methods. As follows:

@Component public class User { private Address address; @AutoWired public setAddress(Address address) { // custom code this.address=address; }}Copy the code

When using this annotation on constructors, it is important to note that only one constructor in a class is allowed to use this annotation. In addition, after Spring4.3, if a class has only one constructor, Spring will automatically inject the associated bean even if this annotation is not used. As follows:

@Component
public class User {
    private Address address;
    
     public User(Address address) {       
        this.address=address;
     }
}

<bean id="user" class="xx.User"/>
Copy the code

@Qualifier

This annotation is used in conjunction with @Autowired. Using this annotation gives you more control over the injection process.

The @qualifier can be used on arguments to individual constructors or methods. When the context has several beans of the same type, using @Autowired makes it impossible to distinguish which beans to bind, you can use @Qualifier to specify the name. A complete PDF version of the Java Interview handbook has been organized into a document

@Component public class User { @Autowired @Qualifier("address1") private Address address; . }Copy the code

@Configuration

This annotation is used to define beans on the class. It acts like an XML configuration file, indicating that the bean is a Spring configuration. In addition, this class can use the @Bean annotation to initialize the definition Bean.

@Configuartion public class SpringCoreConfig { @Bean public AdminUser adminUser() { AdminUser adminUser = new AdminUser(); return adminUser; }}Copy the code

@ComponentScan

This annotation is typically used with the @Configuration annotation to specify the package that Spring scans for the annotation. If no package is specified, the package in which this configuration class resides is scanned by default.

@Lazy

This annotation is used on Spring’s component classes. By default, Bean dependencies in Spring are created and configured from the start. If you want to lazily initialize a bean, you can use Lazy annotations on this class to indicate that the bean will only be created and initialized the first time it is used. This annotation can also be used on classes annotated by @Configuration to indicate that all methods annotated by @Bean are deferred initialization.

@Value

This annotation is used on fields, constructor parameters, and method parameters. @value can specify an expression for the Value of a property, using #{} with SpringEL, or using ${} to inject values from property sources (Properties files, local environment variables, system Properties, and so on) into bean Properties. This annotation values injection occurred in AutowiredAnnotationBeanPostProcessor class.

Spring MVC and REST annotations

@Controller

This annotation is used to declare that this class is a Spring Controller on the class, which is a concrete form of the @Component annotation.

@RequestMapping

This annotation can be used on class and Method to map Web requests to a handler class or handler method. When this annotation is used on a Class, it creates a base URL on which all @requestMapping of its methods will be placed.

You can use its Method attribute to limit the HTTP methods that the request matches.

@Controller @RequestMapping("/users") public class UserController { @RequestMapping(method = RequestMethod.GET) public String getUserList() { return "users"; }}Copy the code

In addition, Spring4.3 has introduced a number of @requestmapping variants. As follows:

  • @GetMapping

  • @PostMapping

  • @PutMapping

  • @PatchMapping

  • @DeleteMapping

RequestMapping is configured for the corresponding Method.

@CookieValue

This annotation is used on the parameters of the @requestMapping declaration method to bind the cookie with the corresponding name in the HTTP cookie.

@ReuestMapping("/cookieValue")
      public void getCookieValue(@CookieValue("JSESSIONID") String cookie){

}
Copy the code

Cookie Indicates the COOKIE value whose name is JSESSIONID in the HTTP request.

@CrossOrigin

This annotation is used on class and Method to support cross-domain requests and was introduced after Spring 4.2.

@CrossOrigin(maxAge = 3600) @RestController @RequestMapping("/users") public class AccountController { @CrossOrigin(origins = "http://xx.com") @RequestMapping("/login") public Result userLogin() { // ... }}Copy the code

@ExceptionHandler

This annotation is used at the method level to declare the processing logic for Exception. You can specify a target Exception.

@InitBinder

This annotation is used on a method to declare the initialization of the WebDataBinder (binding the request parameters to the DataBinder on the JavaBean). Use this annotation on controller to customize the binding of request parameters.

@MatrixVariable

This annotation is used on the parameters of the request Handler method, and Spring can inject the associated values in the Matrix URL. The matrix variables here can appear anywhere in the URL, between the variables; Space. As follows:

// GET /pets/42; q=11; r=22 @RequestMapping(value = "/pets/{petId}") public void findPet(@PathVariable String petId, @MatrixVariable int q) { // petId == 42 // q == 11 }Copy the code

Note that Spring MVC does not support matrix variables by default and needs to be enabled.

<mvc:annotation-driven enable-matrix-variables="true" />
Copy the code

Note configuration needs to be enabled as follows:

@Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configurePathMatch(PathMatchConfigurer configurer) { UrlPathHelper urlPathHelper = new UrlPathHelper(); urlPathHelper.setRemoveSemicolonContent(false); configurer.setUrlPathHelper(urlPathHelper); }}Copy the code

@PathVariable

This annotation is used on the parameters of the request Handler method. RequestMapping can define dynamic paths, such as:

@RequestMapping("/users/{uid}")
Copy the code

You can bind parameters in a path to request method parameters using @pathVariable.

@RequestMapping("/users/{uid}")
public String execute(@PathVariable("uid") String uid){
}
@RequestAttribute
Copy the code

This annotation is used on the parameters of the request Handler method to bind the request Attributes in the Web request (which is the value of the attribute put in by the server) to the method parameters.

@RequestBody

This annotation is used on the parameter of the request Handler method to bind the Body mapping of the HTTP request to this parameter. HttpMessageConverter is responsible for converting an object into an HTTP request.

@RequestHeader

This annotation is used on the parameters of the request Handler method to bind the value of the HTTP request header to the parameters.

@RequestParam

This annotation is used on the parameters of the request Handler method to bind the values of the HTTP request parameters to the parameters.

@RequestPart

This annotation is used on the parameters of the request Handler method to bind multiparts such as files to the parameters.

@ResponseBody

This annotation is used on the request Handler method. Similar to @RequestBody, it is used to output the return object of the method directly to the HTTP response.

@ResponseStatus

This annotation is used on method and exception classes to declare the HTTP status code returned by this method or exception class. You can use this annotation on the Controller so that all @requestMapping inherits. A complete PDF version of the Java Interview handbook has been organized into a document

@ControllerAdvice

This annotation is used on class. We said we can declare ExceptionMethod for each controller. You can use @ControllerAdvice to declare a class that does @ExceptionHandler, @initBinder, and @ModelAttribute processing uniformly for all @RequestMapping methods.

@RestController

This annotation is used on the class to declare that the Controller returns not a view but a domain object. It also introduces the @controller and @responseBody annotations.

@RestControllerAdvice

This annotation is used on class and introduces the @controllerAdvice and @responseBody annotations.

@SessionAttribute

This annotation is used on method parameters to bind attributes in the session to the parameters.

@SessionAttributes

This annotation is used at the Type level to store JavaBean objects into a session. Typically used with the @modelAttribute annotation. As follows:

@modelAttribute ("user") public PUser getUser() {} // Controller and the above code in the same controller @controller@seesionAttributes (value)  = "user", types = { User.class }) public class UserController {}Copy the code

Spring Boot notes

@EnableAutoConfiguration

This annotation is typically used on the main application class to tell Spring Boot to automatically add beans based on the current package, set Bean properties, and so on.

@SpringBootApplication

This annotation is used on the application main class of the Spring Boot project (this class needs to be in the Base Package). Classes that use this annotation first have Spring Boot start component scan the Base Package and classes under its sub-pacakage.

This comment also adds the following comments:

  • @Configuration

  • @EnableAutoConfiguration

  • @ComponentScan

Stereotype annotations

@Component

This annotation is used to declare a Spring component (Bean) on the class, adding it to the application context.

@Controller

I’ve already mentioned that

@Service

This annotation is used on class to declare that this class is a service class that performs business logic, computations, calls internal apis, and so on. Is a concrete form of the @Component annotation.

@Repository

This class uses a class to declare that it is used to access a database, typically in the role of a DAO.

This annotation has automatic translation features. For example, when this component throws an exception, a handler handles the exception without using a try-catch block.

Data access annotations

@Transactional

This annotation is used on an interface definition, a method in the interface, a class definition, or a public method in a class. It is important to note that this annotation does not activate transactional behavior; it is simply metadata that is consumed by some runtime infrastructure.

Vi. Task execution and scheduling notes

@Scheduled

This annotation is used on a method to declare that the method is scheduled. Methods that use this annotation need to return a Void type and cannot accept any arguments.

@Scheduled(fixedDelay=1000)
public void schedule() {

}

@Scheduled(fixedRate=1000)
public void schedulg() { 

}
Copy the code

The second differs from the first in that it does not wait for the last task to finish.

@Async

This annotation is used on a method to declare that the method will be executed in a separate thread. Unlike Scheduled annotations, this one accepts parameters.

The return type of a method using this annotation can be Void or a return value. But the type of the return value must be a Future.

Test notes

@ContextConfiguration

This annotation is used on the Class to declare the configuration file to use for the test, and also to specify the Class for the loading context.

This annotation is typically used with SpringJUnit4ClassRunner. A complete PDF version of the Java Interview handbook has been organized into a document

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringCoreConfig.class)
public class UserServiceTest {

}
Copy the code