In order to facilitate the use of annotations in daily development, this paper unified and classified the annotations needed for development, and analyzed them in combination with use cases, so as to store them for future use. Most importantly, this article will continue to update the annotations in daily use, and others can be informed in the comments.
1 Dependency Injection
1.1 Component annotation @Component
@ Component, @Controller, @Service, and @Repository all combine the @ Component annotation to facilitate categorization of user Class components. By default, components in the IOC container are loaded. When the container is started, it calls the no-parameter constructor to create objects, and then performs initialization and assignment operations
annotations | parsing | usage |
---|---|---|
@Component | Component annotations that automatically scan and load classes into the ICO container when annotated configuration and classpath scanning are used | Comments are on the class |
@Controller | Applied to the MVC layer (the control layer) DispatcherServlet will automatically scan for classes annotated with this annotation and then map web requests to methods annotated with @RequestMapping | Comments are on the class |
@Service | Application in the Service layer (business logic layer | Comments are on the class |
@Repository | Apply at the DAO layer (data access layer) | Comments are on the class |
1.2 Dependency injection annotations
@AutoWired, @Inject, and @Resource can be used together with @qualifier or @name to prevent errors in multi-instance injection and @value injection.
annotations | parsing | usage |
---|---|---|
@Autowired | Through AutowiredAnnotationBeanPostProcessor class implements the dependency injection, default is according to the type of injection, so if there are multiple types of Bean candidate, you will need to qualify a candidate, or it will throw an exception. | Comment on fields, comment on methods |
@Inject | It works the same as @autowired | Comment on fields, on methods, on constructors |
@Resource | By default, assembly is done by name, which can be specified through the name attribute | Comment on fields, comment on methods |
@Qualifier | In addition to injecting by name, qualified descriptors provide more fine-grained control over how candidates are selected. Can be combined with @autowired or @inject for precise injection | Annotate fields, methods, parameters, and annotations |
1.3 Scope and life processes
@scope, which has 4 scopes. See Scope Scope and the problem section involved, as well as the life cycle process handling @postConstruct and @Predestroy.
annotations | parsing | usage |
---|---|---|
@Scope | Have four scope singleton, prototype, session, request, the default is singleton singleton pattern | Annotable at Class creation time |
@PostConstruct | Equivalent to init-method, used on methods and executed when the Bean is initialized | Can be commented on methods |
@PreDestroy | Equivalent to destory-method, used on methods and executed when the Bean is destroyed | Can be commented on methods |
1.4 Section Use Cases (combined with sections 1.1, 1.2, and 1.3)
@service // Component injection, Prototype public class UseFunctionService {@autowired // Default type injection Qualifier("functionService") // Precisely inject functionService functionService; @resource (name="baseDao") private baseDao baseDao; @inject @qualifier ("userServiceImpl") // Precisely Inject public IUserService userService; Public PostConstruct (){system.out.println (" PostConstruct "); Public perDestroy(){system.out.println ("perDestroy");} @predestroy // Public perDestroy(){system.out.println ("perDestroy"); } @Autowired public void setUserDao(@Qualifier("userDao") UserDao userDao) { this.userDao = userDao; } public String SayHello(String word){ return functionService.sayHello(word); }}Copy the code
2. Configure annotations
2.1@Configuration Configuration Comments
@Configuration You can replace the XML Configuration file for Configuration. Be annotated class contains one or more be @ Bean annotation methods, these methods will be AnnotationConfigApplicationContext or AnnotationConfigWebApplicationContext scanned, It is used to build bean definitions and initialize the Spring container. Can be used with @propertysource. @Configuration extends @SpringBootConfiguration as a meta-annotation
annotations | parsing | usage |
---|---|---|
@Configuration | Configuration class annotations, which can be used with @beae and @propertysource for configuration | Comments on classes, interfaces, enumerations |
@SpringBootConfiguration | Combined annotations, @Configuration Configuration, @enableAutoConfiguration enables automatic Configuration, @ComponentScan defaults to scanning the @SpringBootApplication class’s sibling directories and its subdirectories | Annotated on the class |
@AutoConfigureAfter | Configure after the specified auto-configuration class | Annotated on the class |
2.2 Scanning annotations
The @ComponentScan annotation, which is annotated by the @Configuration annotation class, involves the @filter filter annotation
annotations | parsing | usage |
---|---|---|
@ComponentScan | By default, classes with @Controller, @Service, @repository, and @Component annotations will be loaded into the Spring container. ExcludeFilters specify which components to exclude when scanning. IncludeFilters specify only the components to include when scanning | Annotated in Class |
@ComponentScans | Contains the @ComponentScan array | Annotated in Class |
@filter | Declare type filters to be used as include filters or exclude filters | Annotated in @ComponentScan |
2.3 Inject annotations for resources and values
You can inject configuration files, properties in configuration files, and system properties into desired fields, or into beans
annotations | parsing | usage |
---|---|---|
@Value | Value injection, which can inject ordinary characters, system properties, expression results, properties of other beans, file content, url request content, configuration file property values, and so on | Comment on fields, methods, and parameters |
@Bean | Declare the return value of the current method as a Bean, and the corresponding class of the returned Bean can define init() and destroy() methods, and then define them in @bean (initMethod= “init”,destroyMethod= “destroy”). Init after construction and destroy before destruction | Notes on methods, notes |
@PropertySource | Specifies the location of the configuration file to use with the @Configuration class | Annotations on classes, interfaces |
@ImportResource | Load the XML configuration file | Annotations on classes, interfaces |
@ConfigurationProperties | Associate the Properties property with a Bean and its properties | Annotations can be made on classes and interfaces |
@Import | Used to import configuration classes | Annotations can be made on classes and interfaces |
2.4 Conditional Annotation @Conditional
@Conditional creates a particular Bean based on meeting a particular condition, and many Conditional annotations can be extended based on the @Conditional meta-annotation.
annotations | parsing | usage |
---|---|---|
@ConditionalOnBean | If there is an instance in the Spring container, you can find the instance by its type, class name, annotation, nickname (you can configure to find the instance from the current container or the parent container, or both). These properties are arrays and can be found by “and” relationship | Annotate methods |
@ConditionalOnClass | The logic is similar to @conditionalonBean | Annotations can be made on methods, classes, interfaces |
@ConditionalOnExpression | Check whether the SpEL expression is valid | Annotations can be made on methods, classes, interfaces |
@ConditionalOnJava | Specifies whether the Java version meets the requirements | Annotations can be made on methods, classes, interfaces |
@ConditionalOnMissingBean | The logic is similar to @conditionalonbean | Annotations can be made on methods, classes, interfaces |
@ConditionalOnMissingClass | The logic is similar to @conditionalonbean | Annotations can be made on methods, classes, interfaces |
@ConditionalOnNotWebApplication | Whether the application is a non-Web application that provides no attributes, just an identity | Annotations can be made on methods, classes, interfaces |
@ConditionalOnProperty | The logic is similar to @conditionalonBean | Annotations are available on methods, classes, and interfaces |
@ConditionalOnResource | Whether the specified resource file exists. There’s only one property, resources, which is a String array. The Class loader queries the corresponding resource file to see if there are annotable methods, classes, interfaces | |
@Profile | Specify which profile a bean belongs to: spring.profiles.active and spring.profiles.default (default) | Annotations can be made on methods, classes, interfaces |
Chapter 2.5 Use Cases (Sections 2.1, 2.2, 2.3, 2.4)
@Configuration //@SpringBootConfiguration @ComponentScan(value="com.cn",ComponentDefaultFilters=true, includeFilters={ @Filter(type=FilterType.ANNOTATION,classes={Controller.class}), @ Filter (type = FilterType. CUSTOM classes = {MyTypeFilter. Class})}) @ ImportResource (" classpath: condition. The XML ") / / import XML configuration ConditionConfig @import (conditionconfig.class) ConditionConfig class, ConditionConfig public class Config {@value ("I Love You! Private String normal; @value ("#{systemProperties['os.name']}") private String osName; @value ("#{T(java.lang.math).random() * 100.0}") private double randomNumber; @value ("#{demoservice.another}") private String fromAnother; @ Value (" classpath: org/light4j/sping4 / usually/el/test. TXT ") input file contents / / private Resource testFile; @value ("http://www.baidu.com") private Resource testUrl; @value ("${book.name}") private String bookName; @conditional (Windowscondition.class) @conditional (windowscondition.class) condition@conditionalonresource (resources="classpath:windows.ini")// ConditionalOnResource(resources="classpath:windows.ini")// ConditionalOnResource(resources="classpath:windows.ini")// ConditionalOnResource(resources="classpath:windows.ini") Public ListService windowsListService(){return new windowsListService(); } @conditionalonclass (linuxcondition.class) // ConditionalOnClass True @conditionalonProperty (name = "synchronize", HavingValue = "true"))// If Synchronize is in the configuration file and the value is true public ListService linuxListService(){return new LinuxListService(); } // Load the @configurationProperties (prefix = "spring.datasource") public datasource jwcDataSource() { return DataSourceBuilder.create().build(); ({} @ Bean @ ConditionalOnMissingClass LinuxCondition. Class, WindowsCondition class}) / / when container is missing the two class to true Public ListService macListService(){return new macListService(); }}Copy the code
3. Validate annotations
Validation annotations are in the javax.Validation package:
annotations | parsing | usage |
---|---|---|
@Valid | To start validation, the Errors argument should be followed by the @VALID argument, which is the argument to be validated | Comment on fields, methods, constructors, and parameters |
@AssertFalse | The annotated element must be Boolean and have a value of false | Comment on fields, methods, constructors, and parameters |
@AssertTrue | The annotated element must be of Boolean type and have a value of true | Comment on fields, methods, constructors, and parameters |
@DecimalMax | The annotated element must be a number and its value must be less than or equal to the given BigDecimalString value | Comment on fields, methods, constructors, and parameters |
@DecimalMin | The annotated element must be a number and its value must be greater than or equal to the given BigDecimalString value | Comment on fields, methods, constructors, and parameters |
@Digits | The annotated element must be a number, and its value must have the specified number of digits | Comment on fields, methods, constructors, and parameters |
@Future | The value of the annotated element must be a future date | Comment on fields, methods, constructors, and parameters |
@Max | The annotated element must be a number and its value must be less than or equal to the given value | Comment on fields, methods, constructors, and parameters |
@Min | The annotated element must be a number and its value must be greater than or equal to the given value | Comment on fields, methods, constructors, and parameters |
@NotNull | The value of the annotated element must not be NULL | Comment on fields, methods, constructors, and parameters |
@Null | The value of the annotated element must be NULL | Comment on fields, methods, constructors, and parameters |
@Past | The value of the annotated element must be a past date | Comment on fields, methods, constructors, and parameters |
@Pattern | The value of the annotated element must match the given regular expression | Comment on fields, methods, constructors, and parameters |
@Size | The value of the annotated element must be a String, collection, or array, and its length must conform to the given range | Comment on fields, methods, constructors, and parameters |
4.AOP
4.1 Annotated Aspect Programming in AspectJ:
AspectJ’s annotations are in the org.aspectJ package
annotations | parsing | usage |
---|---|---|
@Aspect | Declare the class to be a facet | Annotated on Class and interface |
@After | The notification method is called after the target method returns or throws an exception | Can be annotated in the method |
@Before | The notification method is executed before the target method is called | Can be annotated in the method |
@Around | The notification method encapsulates the target method | Can be annotated in the method |
@AfterReturning | The notification method is called after the target method returns | Can be annotated in the method |
@AfterThrowing | The notification method is called after the target method throws an exception | Can be annotated in the method |
@Pointcut | The ability to define reusable pointcuts within an @AspectJ aspect (using the @Pointcut annotation to declare frequently used Pointcut expressions) | Can be annotated in the method |
@annotation | Qualify to match join points with specified annotations | It can be annotated on advice, such as @after |
@EnableAspectJAutoProxy | Turn on Spring’s support for AspectJ on configuration classes | Annotated on Class and interface |
4.2 AspectJ Indicator
The execution indicator is the primary one we use when writing pointcut definitions:
annotations | parsing | usage |
---|---|---|
AspectJ indicator | describe | |
arg() | Limits the join point matching parameter to the execution method of the specified type | Annotations in AspectJ, such as @after, can be annotated |
@args() | Restrict join point matching parameters by specifying annotation annotation annotation execution methods can be annotated in AspectJ annotations, such as @after, etc | |
execution() | The execution method used to match is the join point | Annotations can be annotated in AspectJ, such as @after, etc |
this() | Restrict join points to match AOP proxy bean references to classes of the specified type | Annotations can be annotated in AspectJ, such as @after, etc |
Target | Classes that restrict join points to match target objects of specified types can be annotated in AspectJ’s annotations, such as @after, etc | |
@target() | Restrict join points to match specific execution objects that correspond to classes with annotations of the specified type | Annotations can be annotated in AspectJ, such as @after, etc |
within() | Restricts the join point to match the specified type | Annotations can be annotated in AspectJ, such as @after, etc |
@within() | Restrict join points to match the type marked by the specified annotation (when using Spring AOP, methods are defined in the class marked by the specified annotation) | Annotations can be annotated in AspectJ, such as @after, etc |
4.3 Use cases: Writing facets
@component public class LogAspect {private final String POINT_CUT ="execution(*) org.sping4.ccww.aop.DemoMethodService.*(..) ) "; The @pointcut (" @ the annotation (org. CCWW. Sping4. Base. Aop. Action) ") / / statement section of the public void annotationPointCut () {}; @after ("annotationPointCut()") Public void after(JoinPoint JoinPoint) {MethodSignature Signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); Action action = method.getAnnotation(Action.class); System.out.println(" annotation interception "+ action.name()); / / 5} @ Before (" execution (* org. Sping4. CCWW. Aop. DemoMethodService. * (..) )" // Declare a recommendation, Public void before(JoinPoint JoinPoint){MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); System.out.println(" method rule intercepting,"+method.getName()); } /* return the following information about the returning value of the first returning parameter: Specifies that a post-return notification can be executed only if the return value of the target method matches the notification method parameter type. Otherwise, no post-return notification can be executed. */ @afterreturning (value = POINT_CUT, RETURNING = "result") public void */ @afterreturning (value = POINT_CUT,returning = "result" DoAfterReturningAdvice1 (JoinPoint JoinPoint,Object result){system.out.println (" first return value: "+result); }}Copy the code
5. Spring MVC
annotations | parsing | usage |
---|---|---|
@EnableWebMvc | Default configurations such as ViewResolver or MessageConverter are enabled | Annotated on Class and interface |
@RequestMapping | For mapping Web requests (access paths and parameters) and handling classes and methods (that is, configuring mappings between urls and methods), the @requestMapping path of annotations on methods inherits the annotation’s path on the class | Annotated on classes, interfaces, and methods |
@ResponseBody | Support putting the return value in the response body | Annotated before a return value or on a method |
@RequestBody | Allow the requ | The est parameters are in the request body |
@PathVariable | Used to receive path parameters, such as/CCWW /003, can receive 003 as a parameter | Can be annotated before parameters |
@RestController | Combining annotations, combining @Controller and @responseBody, means you need to use this annotation when you’re only developing a control that interacts with data on the page. If you don’t have this annotation, you’ll need to add @Controller and @responseBody annotations to your code | Annotated on Class and interface |
@ModelAttribute | Bind request parameters to command objects, expose @requestMapping method returns values as model data, and expose form reference objects as model data | Annotations can be made on methods and parameters |
Use cases:
@controller // declare this class to be a Controller @requestMapping ("/ CCWW ") // Map this class to the access path/CCWW // @restController // declare this class to be a Controller, @responseBody // @requestMapping ("/ CCWW ") public class DemoAnnoController {ResponseBody // @requestMapping ("/ CCWW ") public class DemoAnnoController { Produces produces the returned response media type and character set, or json object, set Porduces ="application/json; charset=UTF-8" @RequestMapping(produces = "text/plain; Charset = utF-8 ") public @responseBody String index(HttpServletRequest Request) { You can also accept HttpServletResponse as an argument. Return "url:" + request.getrequestURL () + "can access"; } @RequestMapping(value = "/demoPathVar/{str}", produces = "text/plain; Charset = utF-8 ")// public @responseBody String demoPathVar(@pathvariable String STR, // Accept path parameter and use @pathvariable before method parameter, / CCW/demopathvar/xxx HttpServletRequest Request) {return "url:" + request.getrequestURL () + "can access, STR: / CCW/demopathvar/xxx HttpServletRequest request) " + str; } // The normal request parameter is/CCWW /requestParam? id=1 @RequestMapping(value = "/requestParam", produces = "text/plain; charset=UTF-8") public @ResponseBody String passRequestParam(Long id, HttpServletRequest request) { return "url:" + request.getRequestURL() + " can access,id: " + id; } @RequestMapping(value = "/obj", produces = "application/json; Public String passObj(DemoObj obj, HttpServletRequest request) { return "url:" + request.getRequestURL() + " can access, obj id: " + obj.getId()+" obj name:" + obj.getName(); } // Map different paths to the same method. The access path is /anno/name1 or /anno/name2 @requestMapping (value = {"/name1", "/name2"}, produces = "text/plain; charset=UTF-8") public @ResponseBody String remove(HttpServletRequest request) { return "url:" + request.getRequestURL() + " can access"; } @requestMapping (value = "/helloWorld") // Add "user" to model object for view page display using public String helloWorld(@modelAttribute user) user) { return "helloWorld"; }}Copy the code
6.Spring security
Spring Security user access authentication and authorization, two key notes:
annotations | parsing | usage |
---|---|---|
@EnableWebSecurityConfig | The annotations and @ Configuration annotations are used together, annotations WebSecurityConfigurer types of classes, or using the @ EnableWebSecurity annotations inherit WebSecurityConfigurerAdapter class, This forms the configuration of Spring Security | Annotated on Class |
@EnableGlobaleMethodSecurity | Spring security is disabled by default annotations, want to open the annotation, we need to inherit WebSecurityConfigurerAdapter class and add @ EnableGlobalMethodSecurity annotations, judge whether the user for a way to control the layers have access | Annotable on Class |
With the parameters of the @ EnableGlobaleMethodSecurity want to open the comments:
- @ EnableGlobalMethodSecurity (securedEnabled = true) : open @ Secured notes filtering permissions
- @ EnableGolablMethodSecurity (jsr250Enabled = true) : open @ RolesAllowed annotation filtering permissions
- @ EnableGlobalMethodSecurity (prePostEnable = true) : use Spring_EL expression more fine-grained access control
The specific open annotation parsing is as follows:
annotations | parsing | usage |
---|---|---|
@Secured | Verify whether access permission is granted | Annotate methods |
@RolesAllowed | The method can be accessed by having permissions on either of its arguments (you can omit the prefix ROLE_) | Can be annotated in the method |
@DenyAll | Deny all access | Can be annotated in the method |
@PermitAll | Allow all access | Can be annotated in the method |
@PreAuthoriz | The method is executed before the method is executed, and the method’s parameters can be called and their values can be obtained | Can be annotated in the method |
@PostAuthorize | It is executed after the method is executed, and the return value of the method can be called here. If EL is false, the method is also finished and may be rolled back | Can be annotated in the method |
@PreFilter | Before the method is executed, and you can call the method’s parameters and filter or process the parameter values. The EL variable filterObject represents the parameters, and if there are multiple parameters, use the filterTarget annotation parameter | Can be annotated in the method |
@PostFilter | Execute after the method executes, and here you can filter the results of the method through expressions | Can be annotated in the method |
Use cases: two critical comments @ EnableWebSecurityConfig, @ EnableGlobaleMethodSecurity:
@ Configuration @ EnableWebSecurity / / open webSecurityConfig @ EnableGlobalMethodSecurity (prePostEnabled = true. SecuredEnabled = true) more annotations can be opened, / / public class WebSecurityConfig extends WebSecurityConfigurerAdapter {... }Copy the code
Other notes:
@secured ("IS_AUTHENTICATED_ANONYMOUSLY")// @secured, anonymous access to public Account readAccount(Long ID){... } @secured ("ROLE_TELLER")// @secured annotation with TELLER access public Account readAccount(Long ID){... } @ PreAuthorize (" # userId = = authentication. Principal. UserId or hasAuthority (' ADMIN ') ") / / using Spring Security @ P annotation parameters, Public void changPassword(@p ("userId")long userId){... } @preauthorize ("hasAuthority('ADMIN')")//PreAuthorize ("hasAuthority('ADMIN')") public void changePassword(long userId){... }Copy the code
6. Spring Boot
annotations | parsing | usage |
---|---|---|
@SpringBootApplication | Spring Boot core annotations, combined annotations (@Configuration, @EnableAutoConfiguration, @ComponentScan), mainly to enable automatic Configuration | Annotations are in the Class interface |
@EnableAutoConfiguration | Have Spring Boot automatically configure the current project based on jar package dependencies in the classpath | Comment on Class and interface |
8. More annotations (test test, @enablexxx, Spring Boot, Spring Cloud annotations, etc.) will be updated later.
Is everyone still ok? If you like, move your hands to show 💗, point a concern!! Thanks for your support!
Welcome to pay attention to the public number [Ccww technology blog], original technical articles launched at the first time