@EnableAutoConfiguration loads custom META-INF without scanning

Keywords: Spring SpringBoot xml MySQL

In this paper, a simple simulation of auto-configuration is performed to understand the process of auto-configuration.And we wrote a small example to test it.

Automatic assembly: The purpose is to load the required module components without the developer using @ComponentScan @EnableXXX.
SpringBoot uses @EnableAutoConfiguration to load META-INF/spring.factories under their respective projects.All items: META-INF/spring.factories in jar package, pom.xml must have a corresponding jar package import before META-INF/spring.factories can be read

@EnableAutoConfiguration actively reads META-INF/spring.factories in three places:
1. META-INF for this project
2. META-INF in jar package imported by POM.xml
3. springboot Global spring-boot-autoconfigure

@EnableXXX Summary
@Import (class object)
1. Class objects are module component class objects (@Configuration @Bean)
2. Import interface (ImportSelector) implementation class that returns an array of module component object names

1. Write a @Configuration first

@Configuration
public class PersonConfiguration {

    @Bean
    public worker getWorker() {
        return new worker();
    }

    @Bean
    public banker getBanker() {
        return new banker();
    }
}

2. Write a custom @EnableXXX

Import the @Configuration just now through @Import

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(PersonConfiguration.class)
public @interface EnablePerson {
}

3. Define another class to use this annotation

@Configuration
@EnablePerson
@ConditionalOnProperty( name = "person",havingValue = "true")
//@ConditionalOnClass(com.wgc.entity.live.class)
@ConditionalOnBean( name = "say" )
public class EnableAutoPerson {
}

4. Custom spring.factories under META-INF

This is what we want to tell SpringBoot AutoConfiguration to include the components we write as well

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.wgc.config.EnableAutoBConfiguration,\
com.wgc.config.EnableAutoPerson

5. Test it

This allows us to load our local resources into containers using @EnableAutoConfiguration without scanning

@SpringBootConfiguration
@EnableAutoConfiguration
public class TestRun {

    @Bean
    public String say() {
        return "dddd say";
    }

    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(TestRun.class)
                .web(WebApplicationType.NONE)
                .run(args);

        String book = context.getBean("mysql",String.class);
        System.out.println("book bean : =="+book);
        banker banker = context.getBean("getBanker",banker.class);
        System.out.println("banker bean : =="+banker.say());
    }
}
Four original articles were published. 0% praised. 25% visited
Private letter follow

Posted by danesc on Thu, 12 Mar 2020 17:48:43 -0700