Spring framework annotation development

Annotation development

1) The meaning of annotation-driven

1.1) What is annotation driven

When the annotation is started, the xml configuration is replaced by the annotation form, which completely eliminates the complicated spring configuration file from the project and simplifies the writing

Insert picture description here

1.2) Disadvantages of annotation-driven

  • In order to achieve the purpose of annotation-driven, the original simple writing may become more complicated
  • It is very convenient to configure resources developed by third parties in XML, but using annotation-driven cannot be edited in resources developed by third parties, so it will increase the workload of development

Insert picture description here

2) Common notes

2.1) Start annotation function

  • Start annotation scanning, load annotation items configured in the class

    <context:component-scan base-package="packageName"/>
    
  • Description:

    • When the package is scanned, all files in the configured package and its sub-packages will be scanned
    • The scanning process is carried out in the form of recursive iteration of folders
    • The scanning process only reads legitimate java files
    • Only read the annotations that spring can recognize when scanning
    • After the scan is over, the identifiable valid annotations will be converted into spring corresponding resources and added to the IoC container
  • note:

    • Regardless of the annotation format or the XML configuration format, the resources are ultimately loaded into the IoC container. The only difference is the way the data is read.
    • In terms of loading efficiency, annotations are better than XML configuration files

2.2) definition of bean

  • 名称:@Component @Controller @Service @Repository

  • Type: Class annotation

  • Location: Above the class definition

  • Role: Set this class as a bean managed by spring

  • example:

    @Component
    public class ClassName{
          
          }
    
  • Description:

    • @Controller, @Service, @Repository are derivative annotations of @Component, with the same functions as @Component
  • Related attributes

    • value (default): defines the access id of the bean

2.3) Scope of bean

  • Name: @Scope

  • Type: Class annotation

  • Location: Above the class definition

  • Role: set the class as the corresponding scope attribute of the bean

  • example:

    @Scope
    public class ClassName{
          
          }
    
  • Related attributes

    • value (default): defines the scope of the bean, the default is singleton

2.4) Bean's life cycle

  • Name: @PostConstruct, @PreDestroy

  • Type: Method annotation

  • Location: Above the method definition

  • Role: Set the class as the life cycle method corresponding to the bean

  • example:

    @PostConstruct
    public void init() {
          
           System.out.println("init..."); }
    

2.5) Load third-party resources

  • Name: @Bean

  • Type: Method annotation

  • Location: Above the method definition

  • Role: Set the return value of the method as a bean managed by spring

  • example:

    @Bean("dataSource")
    public DruidDataSource createDataSource() {
          
              return ……;    }
    
  • Description:

    • Because third-party beans cannot be modified on their source code, use @Bean to solve the problem of introducing third-party beans
    • This annotation is used to replace the static factory and instance factory in the XML configuration to create beans, and does not distinguish whether the method is static or non-static
    • The class where @Bean is located must be scanned and loaded by spring, otherwise the annotation will not take effect
  • Related attributes

    • value (default): defines the access id of the bean

2.6) Non-reference type attribute injection of bean

  • Name: @Value

  • Type: attribute annotation, method annotation

  • Position: Above the attribute definition, above the method definition

  • Role: Set the value of the corresponding attribute or pass parameters to the method

  • example:

    @Value("${jdbc.username}")
    private String username;
    
  • Description:

    • The value value only supports non-reference type data, all parameters of the method are assigned when assigning values
    • The value value supports reading the attribute value in the properties file, and passing the data in the properties into the class through the class attribute
    • Value value supports SpEL
    • If the @value annotation is added above the attribute, the set method can be omitted (the purpose of the set method is to assign a value to the attribute)
  • Related attributes

    • value (default): define the corresponding attribute value or parameter value

2.7) Bean reference type attribute injection

  • Name: @Autowired, @Qualifier

  • Type: attribute annotation, method annotation

  • Position: Above the attribute definition, above the method definition

  • Role: Set the object of the corresponding attribute or pass the reference type to the method

  • example:

    @Autowired(required = false)
    @Qualifier("userDao")
    private UserDao userDao;
    
  • Description:

    • @Autowired is assembled by type by default. After @Qualifier is specified, the id of the bean to be automatically assembled can be specified
  • Related attributes

    • required: Define whether the attribute is allowed to be null

2.8) Bean reference type attribute injection

  • Name: @Primary

  • Type: Class annotation

  • Location: Above the class definition

  • Role: Set the bean corresponding to the class to be assembled first when assembled by type

  • example:

    @Primary
    public class ClassName{
          
          }
    
  • Description:

    • @Autowired is assembled by type by default. When beans of the same type appear, use @Primary to increase the priority of automatic assembly by type. Multiple @Primary will cause the priority setting to be invalid

2.9) Bean reference type attribute injection

  • Name: @Inject, @Named, @Resource
  • Description:
    • @Inject and @Named are annotations in the JSR330 specification, their functions are exactly the same as @Autowired and @Qualifier, which are suitable for different architecture scenarios
    • @Resource is an annotation in the JSR250 specification, which can simplify the writing format
  • @Resource related attributes
    • name: Set the id of the injected bean
    • type: Set the type of the injected bean, the received parameter is the Class type

2.10) Load the properties file

  • Name: @PropertySource

  • Type: Class annotation

  • Location: Above the class definition

  • Role: Load the property value in the properties file

  • example:

    @PropertySource(value = "classpath:filename.properties")
    public class ClassName {
          
          
        @Value("${propertiesAttributeName}")
        private String attributeName;
    }
    
  • Description:

    • The *wildcard format is not supported. Once loaded, the corresponding attribute values ​​can be used in all spring-controlled beans
  • Related attributes

    • value (default): set the name of the loaded properties file
    • ignoreResourceNotFound: If the resource is not found, whether to ignore it, the default is false

2.11) Pure annotation format

  • Name: @Configuration, @ComponentScan

  • Type: Class annotation

  • Location: Above the class definition

  • Role: Set the current class as the spring core configuration loading class

  • example:

    @Configuration
    @ComponentScan("scanPackageName")
    public class SpringConfigClassName{
          
          
    }
    
  • Description:

    • The core matching class is used to replace the spring core configuration file. This class can be set to empty without setting variables and attributes
    • Bean scanning work is replaced by annotation @ComponentScan

AnnotationConfigApplicationContext

  • To load a pure annotation format context object, you need to use AnnotationConfigApplicationContext

    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    

2.12) Third-party bean configuration and management

  • Name: @Import

  • Type: Class annotation

  • Location: Above the class definition

  • Role: Import third-party beans as resources controlled by spring

  • example:

    @Configuration
    @Import(OtherClassName.class)
    public class ClassName {
          
          
    }
    
  • Description:

    • @Import annotations are on the same class, only allowed to be added once, if you need to import more than one, use the form of an array to set
    • In the imported class, you can continue to use @Import to import other resources (understand)
    • The class where @Bean is located can be imported into the spring container in the form of import, without being declared as a bean

3) Bean loading control

3.1) Dependency loading

(1)@DependsOn

  • Name: @DependsOn

  • Type: class annotation, method annotation

  • Location: the location of the bean definition (on the class or on the method)

  • Role: Control the loading order of beans, so that they can be loaded after the specified bean is loaded

  • example:

    @DependsOn("beanId")
    public class ClassName {
          
          
    }
    
  • Description:

    • Configure on the method so that the bean specified by @DependsOn is loaded prior to the bean configured by @Bean
    • Configured on the class, so that the bean specified by @DependsOn is loaded prior to all @Bean configured beans in the current class
    • Configure on the class so that the bean specified by @DependsOn is loaded prior to the bean configured by @Component etc.
  • Related attributes

    • value (default): set the id of the bean that the current bean depends on

(2)@Order

  • Name: @Order

  • Type: configuration annotation

  • Location: The location of the configuration class definition (on the class)

  • Role: Control the loading order of configuration classes

  • example:

    @Order(1)
    public class SpringConfigClassName {
          
          
    }
    

(3)@Lazy

  • Name: @Lazy

  • Type: class annotation, method annotation

  • Location: the location of the bean definition (on the class or on the method)

  • Role: Control the loading timing of the bean to delay loading

  • example:

    @Lazy
    public class ClassName {
          
          
    }
    

3.2) Rely on loading application scenarios

@DependsOn

  • WeChat subscription number, the loading sequence control of the beans that publish and subscribe to messages
  • During the Double 11 event, settlement strategy A is before zero o’clock, settlement strategy B is after zero o’clock, and the operation data of strategy B is promotion data. Strategy B loading sequence and promotion data loading sequence

@Lazy

  • The corresponding emergency plan after the program disaster occurs is the loading time when the container is started

@Order

  • After multiple types of configurations appear, load system-level ones first, and then load business-level ones to avoid fine-grained load control

4) Integrate third-party technology

4.1) Comprehensive case revision (annotation integration MyBatis)

Insert picture description here

4.2) Annotation integration MyBatis analysis

  • The business class uses the annotation form to declare the bean, and the attribute uses the annotation injection
  • Establish an independent configuration management class, classify and manage external resources, classify according to functions, and provide corresponding methods to obtain beans
  • Use the annotation form to start bean scanning, load all annotation configuration resources (bean)
  • Use the AnnotationConfigApplicationContext object to load all startup configuration classes, and use the import method to associate internally

4.3) Annotate the steps of integrating MyBatis

1. Modify the format of mybatis external configuration file to comment format

2. The business class uses @Component to declare beans and @Autowired to inject objects

3. Establish configuration files JDBCConfig and MyBatisConfig classes, and import them into the core configuration class SpringConfig

4. Turn on annotation scanning

5. Use the AnnotationConfigApplicationContext object to load configuration items

4.4) Comprehensive case revision (annotation integration Junit)

1. Spring takes over the right to run Junit, using Spring's special Junit class loader

2. Set the corresponding spring container for Junit test cases:

  • Since Spring5.0, the version of Junit must be 4.12 and above
  • Junit is only used for unit testing, you cannot configure the test class of Junit as a bean of spring, otherwise the configuration will be packaged into the project

Import Spring to integrate Junit coordinates

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.1.9.RELEASE</version>
</dependency>

Spring integrated Junit test case annotation format

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

Guess you like

Origin blog.csdn.net/xghchina/article/details/113923800