Spring Annotation Learning: @Configuration, @Bean, @ComponentScan

Keywords: xml Spring

In the past, when learning Spring, using IOC, you need to use xml configuration files to register and set up the build, and so on. Similarly, annotations can also be used to operate. Here are some summaries made by individuals in the process of learning the development of annotations.

1. @Configuration: Tell Spring that the current class class is a configuration class, equivalent to the previous xml file; in @Configuration, it's actually an @Component; to be annotated by @Configuration, the current class can't be final, it can't be an anonymous class;

2. @Bean: Register a component; equivalent to the <bean/> tag previously in the xml file;

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {

You can see that @Bean can be annotated on METHOD, ANNOCITION_TYPE, and @Bean has the following properties to set up:

parameter Default value concept

value

Default to method name bean aliases, interdependent with name, value,name must be consistent if both are used
name Default method name Equivalent to the id of the < bean /> tag in the xml configuration

autowire

Autowire.NO, default does not open automatic assembly  

initMethod

-- Initialization method

destroyMethod

-- Cancellation method

3. @ComponentScan: Specify the package scanning strategy, which is equivalent to the <context:component-scan/> tag in the xml configuration file. Some properties can be set. The common properties are as follows:

parameter Default value or type concept

value

string Specify the package path to scan
excludeFilters Filter [] Eliminate packages that need to be scanned according to a certain strategy

includeFilters

Filter [] According to a certain strategy, only the specified package needs to be scanned and used with useDefaultFilters=false, otherwise it will not work.

useDefaultFilters

true Default Treasure Scanning Strategy

Where excludeFilter and includeFilter are used, the @Filter annotation is needed to specify the policy, as shown in the following examples:

1,Specifies that only scans include@Controller Annotated bean
includeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class})
        },useDefaultFilters = false


2,Specifies that only scans do not contain@Controller Annotated bean
excludeFilters= {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class})
}

The type of Filter above can have the following centralized scanning strategies:

FilterType.ANNOTATION According to the annotation rule, filter the class marked by the specified annotation
FilterType.ASSIGNABLE_TYPE According to the given type
FilterType.ASPECTJ ASPECTJ expression
FilterType.REGEX regular expression
FilterType.CUSTOM Custom Rules

 

Of course, @ComponentScan can write more than one, or it can use @ComponentScans to include more than one @ComponentScan.

@ComponentScans(value = {
        @ComponentScan(value = "com.snail.tool.annocation",
                excludeFilters = {
                @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class})
                }
        ),
        @ComponentScan(value = "com.snail.tool.annocation",
                includeFilters = {
                @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class})
        }
        ,useDefaultFilters = false
        )      
})

To do a test, first test @Configuration and @Bean; define a bean class Student, define a MyConfig configuration class, inject a stu dent type bean into the container, write the test class, see if you can get it;

1,student class
@Data
@ToString
public class Student {

    private int age;
    private String name;

    public Student() {
    }

    public Student(int age, String name) {
        this.age = age;
        this.name = name;
    }
}
----------------------------------------------------------------
2,Myconfig Configuration class
/**
 * @Configuration The purpose is to tell spring that the current class file is a configuration class file
 */
@Configuration
public class MyConfig {

    /**
     * @Bean The function is to register a bean object in the container, change the object type to return value type, and id to method name.
     * Equivalent to bean tags in configuration files
     */
    @Bean()
    public Student student(){
        return new Student(20,"idea");
    }
}
------------------------------------------------------------------
3,Test class
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootAnnocationApplicationTests {


    @Test
    public void contextLoads() {
        ApplicationContext alicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
        Object student = alicationContext.getBean("stu");
        System.out.println(student);
    }
}

//Result:
Student(age=20, name=idea)

Test 2, test excludeFilter: new controller, service, dao, respectively, using @Controller, @service, @Repository annotations, first scan all bean s excluding controller;

1,Myconfig class
@Configuration
@ComponentScan(value = "com.snail.tool.annocation",
        excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class})
        }
)
public class MyConfig {

}

------------------------------------------------------
2,Test class
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootAnnocationApplicationTests {

    @Test
    public void contextLoads1(){
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            System.out.println(beanDefinitionName);
        }
    }

}

Result:

As you can see, there is no controllrt. But why is there myconfig? Because the @Configuration bottom layer uses the @Component annotation;

Test 3, test includeFilter: Scan only includes all the bean s of controller;

1,Myconfig class
@Configuration
@ComponentScan(value = "com.snail.tool.annocation",
        includeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class})
        },useDefaultFilters = false
)
public class MyConfig {

}

------------------------------------------------------
2,Test class
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootAnnocationApplicationTests {

    @Test
    public void contextLoads1(){
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            System.out.println(beanDefinitionName);
        }
    }

}

Result:

Above is a part of my own summary is just the content. When I first learned it, the whole people were silly and finished it. If there is any mistake, please point out, thank you.

Posted by think-digitally on Tue, 23 Apr 2019 20:03:35 -0700