The 7 most commonly used annotations in spring

With the update and iteration of technology, Java 5.0 began to support annotations. As the leading framework in Java, spring has gradually abandoned the xml configuration since the update to version 2.5, and more uses annotations to control the spring framework.

However, there are so many annotations in spring, and it may not be used in java for many years. Here is a summary of the 7 most commonly used annotations by type.

1. Core Notes

@Required
This annotation is used on the setter method of the bean. Indicates that this attribute is required and must be injected during the configuration phase, otherwise BeanInitializationExcepion will be thrown.

@Autowired
This annotation is used to explicitly declare dependencies on the bean's field, setter and construction methods. According to the type to autowiring.

When this annotation is used on a field and attributes are used to pass values, Spring will automatically assign the value to this field. You can also use this annotation for private attributes (not recommended), as follows.

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

The most common usage is to use this annotation on the setter so that you can add custom code in the setter method. as follows:

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

When using this annotation on the constructor, one thing to note is that only one constructor in a class is allowed to use this annotation. In addition, after Spring 4.3, if a class has only one constructor, even if this annotation is not used, Spring will automatically inject related beans. as follows:

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

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

@Qualifier
This annotation is used with @Autowired. Using this annotation allows you to have more control over the injection process.

@Qualifier can be used on the parameters of a single constructor or method. When there are several beans of the same type in the context, @Autowired cannot distinguish the beans to be bound. In this case, @Qualifier can be used to specify the name.

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

@Configuration
This annotation is used on the class to define beans. Its role is the same as the xml configuration file, which means that this bean is a Spring configuration. In addition, this class can use the @Bean annotation to initialize and define the bean.

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

@ComponentScan
This annotation is generally used together with the @Configuration annotation to specify the package of the Spring scan annotation. If no package is specified, the package where this configuration class is located will be scanned by default.

@Lazy
This annotation is used on Spring component classes. By default, Bean dependencies in Spring are created and configured from the beginning. If you want to delay the initialization of a bean, you can use the Lazy annotation on this class, which means that the bean will only be created and initialized when it is used for the first time. This annotation can also be used on classes annotated by @Configuration, which means that all methods annotated by @Bean will be initialized lazily.

@Value
This annotation is used on fields, constructor parameters, and method parameters. @Value can specify the expression of the attribute value, support #{} to use SpringEL to obtain the value, and also support the use of ${} to inject the value of the attribute source (Properties file, local environment variable, system property, etc.) into the bean In the properties. The injection of this annotation value occurs in the AutowiredAnnotationBeanPostProcessor class.

2. Spring MVC and REST annotations

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

@RequestMapping
This annotation can be used on classes and methods to map web requests to a certain handler class or handler method. When this annotation is used on the Class, a basic url is created, and the @RequestMapping on all its methods are on this url.

You can use its method attribute to limit the http method that the request matches.

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

In addition, a series of @RequestMapping variants were introduced after Spring 4.3. as follows:

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @PatchMapping
  • @DeleteMapping

Corresponding to the RequestMapping configuration of the corresponding method.

@CookieValue
This annotation is used on the parameters of the method declared by @RequestMapping to bind the cookie with the corresponding name in the HTTP cookie.

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

}

Cookie is the cookie value whose name is JSESSIONID in the http request.

@CrossOrigin
This annotation is used on classes and methods to support cross-domain requests. It 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() {
        // ...
    }
}

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

@InitBinder
This annotation is used on the method to declare the initialization of the WebDataBinder (bind the request parameters to the DataBinder on the JavaBean). Use this annotation on the 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 relevant values ​​in the matrix url. The matrix variables here can appear anywhere in the url, separated by ;. 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
}

It should be noted that the default Spring mvc does not support matrix variables and needs to be turned on.

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

The annotation configuration needs to be turned on as follows:

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

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

@RequestMapping("/users/{uid}")

You can use @PathVariable to bind the parameters in the path to the request method parameters.

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

This annotation is used on the parameters of the request handler method to bind the attributes in the web request (request attributes, which are attribute values ​​placed by the server) to the method parameters.

@RequestBody
This annotation is used on the parameters of the request handler method to bind the body mapping of the http request to this parameter. HttpMessageConverter is responsible for converting objects into http requests.

@RequestHeader
This annotation is used on the parameters of the request handler method to bind the value of the http request header to the parameter.

@RequestParam
This annotation is used on the parameters of the request handler method to bind the value of the http request parameter to the parameter.

@RequestPart
This annotation is used on the parameters of the request handler method to bind multipart such as files to the parameters.

@ResponseBody
This annotation is used in the request handler method. Similar to @RequestBody, it is used to directly output the returned object of the method to the http response.

@ResponseStatus
This annotation is used on methods 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 will inherit.

@ControllerAdvice
This annotation is used on the class. As mentioned earlier, you can declare an ExceptionMethod for each controller. Here you can use @ControllerAdvice to declare a class to uniformly handle all @RequestMapping methods @ExceptionHandler, @InitBinder, and @ModelAttribute.

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

@RestControllerAdvice
This annotation is used on the class, and two annotations @ControllerAdvice and @ResponseBody are also introduced.

@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 in the session. Generally used with @ModelAttribute annotation. as follows:

@ModelAttribute("user")

public PUser getUser() {}

// controller和上面的代码在同一controller中
@Controller
@SeesionAttributes(value = "user", types = {
    User.class
})

public class UserController {}

Three. Spring Boot annotation

@EnableAutoConfiguration
This annotation is usually used in the main application class to tell Spring Boot to automatically add beans based on the current package and set bean properties.

@SpringBootApplication
This annotation is used in the application main class of the Spring Boot project (this type needs to be in the base package). The class with this annotation will firstly start Spring Boot to perform component scan on the base package and the classes under its sub-pacakage.

This note also adds the following notes:

  • @Configuration
  • @EnableAutoConfiguration
  • @ComponentScan

Four. Stereotype annotation

@Component
This annotation is used on the class to declare a Spring component (Bean) and add it to the application context.

@Controller
mentioned before

@Service
This annotation is used on the class to declare that this class is a service class, which executes business logic, calculations, and calls internal APIs. It is a specific form of @Component annotation.

@Repository
This class is used to declare this class on the class to access the database, generally as the role of DAO.

This annotation has the feature of automatic translation, for example: when this kind of component throws an exception, then there will be a handler to handle the exception without using a try-catch block.

V. Data Access Notes

@Transactional
This annotation is used in interface definitions, methods in interfaces, class definitions, or public methods in classes. It should be noted that this annotation does not activate transaction behavior, it is just a metadata that will be consumed by some runtime infrastructure.

6. Task execution and scheduling notes

@Scheduled
This annotation is used on methods to declare that this method is scheduled regularly. The return type of the method using this annotation needs to be Void and cannot accept any parameters.

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

}

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

}

The second is different from the first in that it will not wait for the completion of the previous task execution.

@Async
This annotation is used on methods, stating that this method will be executed in a separate thread. Unlike the Scheduled annotation, this annotation can accept parameters.

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

7. Test notes

@ContextConfiguration
This annotation is used on Class to declare the configuration file used by the test. In addition, you can also specify the class to load the context.

This annotation generally needs to be used with SpringJUnit4ClassRunner.

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

}

Guess you like

Origin blog.csdn.net/Lubanjava/article/details/100579554