Spring’s 7 most commonly used categories of annotations, the most powerful collation in history!
1. Core Notes
The @required annotation is used on setter methods of the bean. 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; }
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; }}
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; }}
@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. @Component public class User { @Autowired @Qualifier(“address1”) private Address address; . }
@Configuration This annotation is used to define beans on a 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; }}
@ComponentScan This annotation is typically used with the @Configuration annotation to specify the package for Spring to scan annotations. 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 arguments, and method arguments. @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
The @Controller annotation is used on the class to declare that this class is a Spring Controller, and 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”; }}
Spring MVC common annotations are also recommended for this article. In addition, Spring4.3 has introduced a number of @requestmapping variants. @GetMapping@PostMapping@PutMapping@PatchMapping @deletemapping corresponds to the RequestMapping configuration of the corresponding method. Follow wechat public number: Java community, in the background reply: Spring, I can get the latest N spring tutorials, are dry goods. @Cookievalue This annotation is used on the parameters of the @requestMapping declared method to bind the cookie with the corresponding name in the HTTP cookie. @ReuestMapping(“/cookieValue”) public void getCookieValue(@CookieValue(“JSESSIONID”) String cookie){ } Cookie Indicates 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 and was introduced after Spring 4.2. @CrossOrigin(maxAge = 3600) @RestController @RequestMapping(“/users”) public class AccountController { @CrossOrigin(origins = “xx.com”) @RequestMapping(“/login”) public Result userLogin() { // … }}
@ExceptionHandler This annotation is used at the method level to declare the logic to handle Exception. You can specify a target Exception. InitBinder This annotation is used on methods to declare initialization of the WebDataBinder (bind 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 values associated with the matrix URL. The matrix variables here can appear anywhere in the URL, between the variables; Space. // GET /pets/42; q=11; r=22 @RequestMapping(value = “/pets/{petId}”) public void findPet(@PathVariable String petId, @MatrixVariable int q) { // petId == 42 // q == 11 }
Note that Spring MVC does not support matrix variables by default and needs to be enabled.
<mvc:annotation-driven enable-matrix-variables=”true” />
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); }}
@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 bind parameters in a path to request method parameters using @pathVariable. @RequestMapping(“/users/{uid}”) public String execute(@PathVariable(“uid”) String uid){ }
Follow wechat public number: Java community, in the background reply: Spring, I can get the latest N spring series of procedures, are dry goods. @requestAttribute This annotation is used on the parameters of the request Handler method to bind the request Attributes in the Web request to the method parameters. The @requestBody 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 RequestHeader 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. @controllerAdvice This annotation is used on the 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 a 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 the class and introduces the @ControllerAdvice and @responseBody annotations. @sessionAttribute This attribute is used on method parameters to bind session attributes to 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 @seesionAttributes (value = “user”, types = {user.class}) @controller @seesionAttributes (value = “user”, types = {user.class})
public class UserController {}
3 Spring Boot annotations
@enableAutoConfiguration This annotation is usually 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 SpringBoot 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 annotation is accompanied by the following annotations: @Configuration@EnableAutoConfiguration@ComponentScan
4 Stereotype annotations
The @component annotation is used to declare a Spring Component (Bean) on the class, adding it to the application context. This annotation is used on a class to declare that this class is a Service class that performs business logic, computations, calls internal apis, etc. Is a concrete form of the @Component annotation. The @repository class is used to declare this class on a class to access a database, typically acting as 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.
5 Data access annotations
The Transactional 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.
6 Task execution and scheduling comments
@scheduled This annotation is used on a method to state 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() {
}
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.
7 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 to load the context of. This annotation is typically used with SpringJUnit4ClassRunner. @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SpringCoreConfig.class) public class UserServiceTest {
Every book we read and every language we learn will give us an unexpected return in the future. In fact, as a developer, it is particularly important to have a learning atmosphere and a communication circle. Here I recommend a Java learning exchange group 342016322. No matter you are small white or big bull, welcome to enter.