认识META-INF/spring.factories文件

原文地址 https://www.cnblogs.com/java-quan/p/13643041.html

平常我们如何将 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文件去进行加载的。

posted @ 2021-02-27 10:24  寒小韩  阅读(1341)  评论(0编辑  收藏  举报