建立META-INF/spring.factories文件的意義何在


平常我們如何將Bean注入到容器當中

@Configuration
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {

    @Autowired
    HelloProperties helloProperties;

    @Bean
    public HelloService helloService() {
        HelloService service = new HelloService();
        service.setHelloProperties( helloProperties  );
        return service;
    }
}

一般就建立配置文件使用@Configuration,里面通過@Bean進行加載bean

或者使用@Compont注解在類上進行類的注入

注意:

在我們主程序入口的時候:

@SpringBootApplication這個注解里面的東西

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

里面注解@EnableAutoConfiguration

@ComponentScan注解指掃描@SpringBootApplication注解的入口程序類所在的basepackage下的

所有帶有@Component注解的bean,從而注入到容器當中。

但是

如果是加入maven坐標依賴的jar包,就是項目根目錄以外的Bean是怎么添加的??

這個時候注解@EnableAutoConfiguration的作用就來了

導入了AutoConfigurationImportSelector這個類:

這個類里面有一個方法

    /**
     * Return the auto-configuration class names that should be considered. By default
     * this method will load candidates using {@link SpringFactoriesLoader} with
     * {@link #getSpringFactoriesLoaderFactoryClass()}.
     * @param metadata the source metadata
     * @param attributes the {@link #getAttributes(AnnotationMetadata) annotation
     * attributes}
     * @return a list of candidate configurations
     */
    protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
        List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
                getBeanClassLoader());
        Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
                + "are using a custom packaging, make sure that file is correct.");
        return configurations;
    }

@EnableAutoConfiguration注解來注冊項目包外的bean。而spring.factories文件,則是用來記錄項目包外需要注冊的bean類名

 

為什么需要spring.factories文件,
因為我們整個項目里面的入口文件只會掃描整個項目里面下的@Compont @Configuration等注解
但是如果我們是引用了其他jar包,而其他jar包只有@Bean或者@Compont等注解,是不會掃描到的。
除非你引入的jar包沒有Bean加載到容器當中
所以我們是通過寫/META-INF/spring.factories文件去進行加載的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM