With the iterative update technology, Java5.0 began to support annotations. As a leader in the spring java framework, since the updated 2.5 version began to slowly abandon the xml configuration, greater use of annotations to control the spring frame.
The spring of the comments are so many, many years of java might do, do not have access. Here by type summarizes the seven most common comment.
A core notes
@Required
This annotation is used on the setter methods bean. It indicates that this property is necessary, must be injected in the configuration phase, otherwise it will throw BeanInitializationExcepion.
@Autowired
This annotation is used on the bean field, setter method and construction method explicitly declared dependency. According to the type autowiring.
When using this annotation on a field, and use the property to pass values, Spring automatically assign a value to this field. This comment can also be used for private property (not recommended), follows.
@Component
public class User {
@Autowired
private Address address;
}
This usage is most often used to comment on settter, so you can add custom code in 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 the constructor, the point to note is that a class has a constructor method only allows the use of this annotation. In addition, after Spring4.3, if a class has only one constructor, even if does not use this annotation, then Spring will automatically be associated bean injection. 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 and @Autowired. Using this annotation allows you to have more control over the process of implantation.
@Qualifier can be used on a single parameter or a constructor method. When there are several of the same type of context bean, it can not be distinguished using @Autowired bean to be bound, can now be used to specify the name @Qualifier.
@Component
public class User {
@Autowired
@Qualifier("address1")
private Address address;
...
}
@Configuration
This comment came up with the class defined bean. Its role and the same xml configuration file, indicates that this is a Spring bean configuration. In addition, such annotations can be used to initialize @Bean defined bean.
@Configuartion
public class SpringCoreConfig {
@Bean
public AdminUser adminUser() {
AdminUser adminUser = new AdminUser();
return adminUser;
}
}
@ComponentScan
This annotation is generally used with @Configuration notes, annotations specified package Spring scan. If the package is not specified, the default configuration will scan package this class is in.
@Lazy
This annotation using a Spring component class. Default, Spring Bean in dependence outset be created and configured. If you want to delay the initialization of a bean, you can use Lazy comment on such, this bean represents only the first time to be used will be created and initialized. This annotation can be used in the @Configuration annotated class, which represents all @Bean annotated methods will delay initialization.
@Value
This annotation used in the field, the configuration parameters and method parameters. @Value can specify property values of the expression, # {} used by support to SpringEL value, also supports $ {} to be injected into the source attribute value (Properties file, the local environment variables, system properties and the like) to the bean of property. This injection occurs in the value of annotation AutowiredAnnotationBeanPostProcessor class.
Two. Spring MVC and REST annotations
@Controller
This annotation in the class declaration class is a Spring controller, it is a specific form of @Component comment.
@RequestMapping
This annotation can be used in class and method, used to map a web request to a handler handler class or method. When used in this comment Class, on the creation of a foundation url, which @RequestMapping on all methods are at the top of this url.
Which may be used to limit the method attribute matches request http method.
@Controller
@RequestMapping("/users")
public class UserController {
@RequestMapping(method = RequestMethod.GET)
public String getUserList() {
return "users";
}
}
In addition, after the introduction of a series of Spring4.3 @RequestMapping variants. as follows:
@GetMapping
@PostMapping
@PutMapping
@PatchMapping
@DeleteMapping
correspond to the respective method of RequestMapping configuration.
@CookieValue
This annotation parameters used in the method of @RequestMapping statement, you can put the cookie HTTP cookie to bind up the appropriate name.
@ReuestMapping("/cookieValue")
public void getCookieValue(@CookieValue("JSESSIONID") String cookie){
}
cookie i.e., an http request is the name of the cookie value JSESSIONID.
@CrossOrigin
This annotation used in the class and method to support cross-domain request, after the introduction of 4.2 Spring.
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/users")
public class AccountController {
@CrossOrigin(origins = "http://xx.com")
@RequestMapping("/login")
public Result userLogin() {
// ...
}
}
@ExceptionHandler
This annotation using the method level, claims processing logic of Exception. You can specify the target Exception.
@InitBinder
This annotation on the method used, the statement WebDataBinder initialized (DataBinder bind request to the parameter JavaBean). Use annotations on this controller can request custom binding parameters.
@MatrixVariable
This annotation handler for that request the use of the method, Spring matrix url may be injected into the relevant values. Anywhere herein matrix variables can appear in the url, with between the variable; separated. 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
}
Note that the default Spring mvc does not support matrix variable, we need to open.
<mvc:annotation-driven enable-matrix-variables="true" />
Notes configuration you need to open the following:
@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 handler for that request the use of the method. @RequestMapping can define the dynamic path, such as:
@RequestMapping("/users/{uid}")
@PathVariable path may be used to bind the parameter to the parameter request method.
@RequestMapping("/users/{uid}")
public String execute(@PathVariable("uid") String uid){
}
@RequestAttribute
This annotation handler used in the method of the parameters of the request, the request for the web properties (request attributes, the attribute value is placed in the server's) bound to the method parameters.
This annotation handler used in the method of the parameters of the request, the request for the web properties (request attributes, the attribute value is placed in the server's) bound to the method parameters.
@RequestBody
This annotation used for that request handler method for mapping Body bound to the http request of the parameters. HttpMessageConverter responsible for converting objects to http requests.
@RequestHeader
This annotation used for that request handler method for the http request header to the value of the parameter bind.
@RequestParam
This annotation used for that request handler method for binding values of parameters to the http request parameter.
@RequestPart
This annotation used for that request handler method for the multipart document or the like bound to the parameters.
@ResponseBody
This annotation handler method used in the request. And @RequestBody similar effect, a method for directly output to return object http response.
@ResponseStatus
This annotation for the methods and exception class declaration exception class or method http status code returned. You can use this annotation on Controller, all such @RequestMapping will inherit.
@ControllerAdvice
this comment for the class. As mentioned above can be a ExceptionMethod statement for each controller. Here you can use @ControllerAdvice to declare a class to do @ ExceptionHandler unified method for all @RequestMapping, @ InitBinder and @ModelAttribute process.
@RestController
this comment for the class, declare this controller is not one but a return to the field of object view. It also introduces @Controller and @ResponseBody two notes.
@RestControllerAdvice
this comment for the class, while the introduction of @ControllerAdvice and @ResponseBody two notes.
@SessionAttribute
this annotation is used on the parameters of the method, for binding to the session attributes parameter.
@SessionAttributes
This annotation is used to type level for JavaBean objects stored in the session. General and @ModelAttribute notes used together. as follows:
@ModelAttribute("user")
public PUser getUser() {}
// controller和上面的代码在同一controller中
@Controller
@SeesionAttributes(value = "user", types = {
User.class
})
public class UserController {}
Three. Spring Boot comment
@EnableAutoConfiguration
This annotation is commonly used in the main application class, tell Spring Boot automatically based on the current package adds Bean, the bean's properties are set and so on.
@SpringBootApplication
This annotation is used in the main application class Spring Boot program (such needs in the base package). Use this annotation class will first start of Spring Boot base package and class under its sub-pacakage be component scan.
This annotation at the same time adds the following comment:
@Configuration
@EnableAutoConfiguration
@ComponentScan
This finish is also very full: the Spring core of the Boot 25 notes , suggest that you look.
Four. Stereotype annotations
@Component
This annotation in a class declaration Spring up assembly (Bean), and added to the application context.
@Controller
As already mentioned
@Service
this comment in the class, such a statement is a service class, perform business logic, calculations, internal api calls and so on. @Component annotation is a specific form.
@Repository
such use of such statements in the class used to access the database, as a general role of DAO.
This annotation has the characteristics of automatic translation, for example: when such a component throws an exception, then there will be a handler to handle this exception, without the use of try-catch block.
V. Data Access Notes
@Transactional
This annotation in interface definitions, method interface, class definitions or the public methods in a class. Note that this comment does not activate the transactional behavior, it is just a metadata will be a number of run-time infrastructure spending.
VI. Task execution, dispatch notes
@Scheduled
This annotation used in the method, this method is declared a timing scheduling. Use this method return type annotation is needed Void, and can not accept any parameters.
@Scheduled(fixedDelay=1000)
public void schedule() {
}
@Scheduled(fixedRate=1000)
public void schedulg() {
}
The second and the first except that it does not wait for the end of the last task execution.
@Async
this comment on the use of the method, this method statement will execute in a separate thread. Unlike Scheduled annotation, this annotation can accept parameters.
Use this annotation method's return type Void may also be a return value. But the type of the return value must be a Future.
VII. Test Notes
@ContextConfiguration
This annotation used on Class, declare tested using configuration files. In addition, you can also specify the load context of class.
This normally takes notes with SpringJUnit4ClassRunner use.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringCoreConfig.class)
public class UserServiceTest {
}
Original author: Road Advanced Development of Java
Original Address: https://blog.csdn.net/Lubanjava/article/details/100579554