Tag: Action will also RAM exec multi hand scheduled activation cannot
Starting with Java5.0, Java begins to support annotations. Spring is the leading framework in the Java ecosystem, and it has been supporting annotations since the 2.5 release. By using XML to configure the spring framework, using annotations provides more control over the spring framework.
Now more and more projects are using annotations to do the relevant configuration, but spring annotations are very many, I believe many annotations have not been used. This article summarizes the most common annotations in spring as a whole.
I. Core Annotations @required
This annotation is used on the bean setter method. Indicates that this property is required and must be injected during the configuration phase, otherwise the beaninitializationexcepion will be thrown.
@Autowired
This annotation is used to explicitly declare dependencies on the bean's field, setter method, and construction method. Autowiring according to type.
When this annotation is used on a field and the property is used to pass the value, spring automatically assigns the value to the field. You can also use this annotation for private properties (not recommended), as follows.
123)45 |
@Componentpublic class User { @Autowired private Address address; }
|
The most common usage is to use this annotation on Settter, which allows you to add custom code to the setter method. As follows:
12345 6789< Span class= "Line-number" >10 |
public class User { private address address; @AutoWired public setaddress (address address) { |
/tbody>
When using this annotation on a construction method, it is important to note that only one constructor method is allowed in a class to use this annotation. Also, after Spring4.3, if a class has only one constructor, spring will automatically inject the relevant bean, even if this annotation is not used. as follows:
123456789 |
@Componentpublic class User { private Address address; public User(Address address) { this.address=address; }}<bean id="user" class="xx.User"/>
|
@Qualifier
This annotation is used in conjunction 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 the context has several beans of the same type, using @autowired does not differentiate between the beans to bind, you can use @qualifier to specify the name.
1234567 |
@Componentpublic class User { @Autowired @Qualifier("address1") private Address address; ...}
|
@Configuration
This annotation uses the class to define the bean. Its role is the same as the XML configuration file, which indicates that this bean is a spring configuration. In addition, this class can use @bean annotations to initialize the definition bean.
12345678 |
@Configuartionpublic class SpringCoreConfig { @Bean public AdminUser adminUser() { AdminUser adminUser = new AdminUser(); return adminUser; }}
|
@ComponentScan
This annotation is typically used in conjunction with @configuration annotations to specify the package for spring scan annotations. If no packages are specified, the package that contains this configuration class is scanned by default.
@Lazy
This annotation is used on the spring component class. By default, bean dependencies in spring are created and configured from the start. If you want to defer initialization of a bean, you can use lazy annotations on this class to indicate that the bean will be created and initialized only when it is first used. This annotation can also be used on a class that is @configuration annotated, indicating that all methods that are @bean annotated are deferred for initialization.
@Value
This annotation is used on fields, constructor parameters, and method parameters. @Value can specify an expression for the value of a property, support using Springel with #{}, and ${} to inject values from the property source (properties file, local environment variable, system property, and so on) into the Bean's properties. The injection of this annotation value occurs in the Autowiredannotationbeanpostprocessor class.
Two. Stereotype Annotations @component
This annotation uses the class to declare a spring component (Bean) and add it to the application context.
@Controller
This annotation uses declaring on class that this class is a spring controller and is a concrete form of @component annotations.
@Service
This annotation is used on class, declaring that this class is a service class that executes business logic, computes, invokes internal APIs, and so on. is a specific form of @component annotations.
@Repository
This class is used to declare this class on class to access the database, generally as a DAO role.
This annotation has an automatic translation feature, for example: When this type of component throws an exception, there is a handler to handle this exception without using the Try-catch block.
Three. Spring Boot annotations @enableautoconfiguration
This annotation is typically used on the main application class, telling spring boot to automatically add beans based on the current package, set the Bean's properties, and so on.
@SpringBootApplication
This annotation is used on the main application class of the Spring Boot project (this class needs to be in the base package). Classes that use this annotation first let Spring boot launch a component scan of the base package and the classes under its sub-pacakage.
This note adds the following annotations at the same time:
- @Configuration
- @EnableAutoConfiguration
- @ComponentScan
Four. Spring MVC and Rest annotations @controller
This note has already been mentioned above.
@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 class, a base URL is created, and all of its methods are @requestmapping on top of this URL.
You can use its Method property to limit the HTTP method that the request matches.
12345678 |
@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 Spring4.3. As follows:
- @GetMapping
- @PostMapping
- @PutMapping
- @PatchMapping
- @DeleteMapping
The requestmapping configuration of the corresponding method is corresponding respectively.
@CookieValue
This annotation is used on the parameters of the method declared by the @requestmapping to bind the cookie of the corresponding name in the HTTP cookie.
1234 |
@ReuestMapping("/cookieValue") public void getCookieValue(@CookieValue("JSESSIONID") String cookie){}
|
The cookie is the cookie value of name Jsessionid in the HTTP request.
@CrossOrigin
This annotation is used on class and method to support cross-domain requests, which are introduced after spring 4.2.
123456789 |
@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 a target exception.
@InitBinder
This annotation is used on methods to declare the initialization of Webdatabinder (binding request parameters to DataBinder on JavaBean). Use this annotation on the controller to customize the binding of the request parameters.
@MatrixVariable
This annotation uses the parameters of the request handler method, spring can inject the relevant values in the Matrix URL. The matrix variables here can appear anywhere in the URL, separated by variables. As follows:
123456 |
// 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 is important to note that the default spring MVC does not support matrix variables and needs to be turned on.
1 |
<mvc:annotation-driven enable-matrix-variables="true" />
|
The annotation configuration needs to be turned on as follows:
123456789 |
@Configurationpublic 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:
1 |
@RequestMapping("/users/{uid}")
|
You can use @pathvariable to bind parameters in a path to a request method parameter.
123 |
@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 property in the Web request (Request attributes, the property value that the server puts in) to the method parameter.
@RequestBody
This annotation is used on the parameters of the request handler method to bind the body map of the HTTP request to this parameter. Httpmessageconverter is responsible for converting the object to 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 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 a file, to a parameter.
@ResponseBody
This annotation is used on the request handler method. Similar to @requestbody, used to output the return object of a method directly to the HTTP response.
@ResponseStatus
This annotation is used on methods and exception classes, declaring the HTTP status code returned by this method or by the exception class. This annotation can be used on a controller so that all @requestmapping are inherited.
@ControllerAdvice
This annotation is used on class. As I said earlier, you can declare a exceptionmethod for each controller. Here you can use @controlleradvice to declare a class that unifies all @requestmapping methods to do @exceptionhandler, @InitBinder, and @modelattribute processing.
@RestController
This annotation is used on class, declaring that the controller returned is not a view but a realm object. It also introduces two annotations of @controller and @responsebody.
@RestControllerAdvice
This annotation is used on class and introduces two annotations of @controlleradvice and @responsebody.
@SessionAttribute
This annotation is used on the parameters of the method to bind the properties in the session to the parameter.
@SessionAttributes
This annotation is used for the type level and is used to store the JavaBean object in the session. Commonly used in conjunction with @modelattribute annotations. As follows:
12 3456< Span class= "Line-number" >78910< Span class= "Line-number" >11 |
public puser GetUser () {}// Controller and the above code in the same controller @SeesionAttributes (value = "User" , types = { User.class}) public class Usercontroller {} |
Five. Data access Annotations @transactional
This annotation is used on the interface definition, the method in the interface, the class definition, or the public method in the class. It is important to note that this annotation does not activate transactional behavior, it is just a meta-data that is consumed by some runtime infrastructure.
Six. Task execution, scheduling annotations @scheduled
This annotation is used on the method, declaring that this method is scheduled on a timed basis. The method return type that uses this annotation needs to be void and cannot accept any arguments.
123456789 |
@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 execution to end.
@Async
This annotation is used on a method that declares that the method executes in a separate thread. Unlike scheduled annotations, this annotation can accept parameters.
The return type of a method that uses this annotation can be either void or return value. But the type of the return value must be a future.
Seven. Test note @contextconfiguration
This annotation is used on class to declare the configuration file used by the test, and also to specify the class that loads the context.
This annotation generally needs to be used with Springjunit4classrunner.
123)45 |
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = SpringCoreConfig.class)public class UserServiceTest {}
|
Spring Annotations Preview