三、SpringBoot——自动配置原理(@EnableAutoConfiguration)

1配置文件怎么写

参看配置文档
https://docs.spring.io/spring-boot/docs/1.5.9.RELEASE/reference/htmlsingle/#common-application-properties

2 自动配置原理(Springboot 1.5.10)

1)、SpringBoot启动的时候加载主配置类,开启了自动配置功能@EnableAutoConfiguration
在这里插入图片描述

2)、@EnableAutoConfiguration 作用:
利用EnableAutoConfigurationImportSelector的父类AutoConfigurationImportSelector#selectImports()方法给容器中导入一些组件
获取候选的配置;

在这里插入图片描述
在这里插入图片描述
(1)AutoConfigurationImportSelector # selectImports()


    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        if (!this.isEnabled(annotationMetadata)) {
            return NO_IMPORTS;
        } else {
            try {
                AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
                AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
                List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);//获取候选的配置
                configurations = this.removeDuplicates(configurations);
                configurations = this.sort(configurations, autoConfigurationMetadata);
                Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
                this.checkExcludedClasses(configurations, exclusions);
                configurations.removeAll(exclusions);
                configurations = this.filter(configurations, autoConfigurationMetadata);
                this.fireAutoConfigurationImportEvents(configurations, exclusions);
                return (String[])configurations.toArray(new String[configurations.size()]);
            } catch (IOException var6) {
                throw new IllegalStateException(var6);
            }
        }
    }

(2)List configurations = getCandidateConfigurations(annotationMetadata, attributes);获取候选的配置
AutoConfigurationImportSelector # getCandidateConfigurations()

    protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
        List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.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;
    }

(3)SpringFactoriesLoader # loadFactoryNames() 扫描所有自动配置jar包类路径下 META‐INF/spring.factories 把扫描到的这些文件的内容包装成properties对象,从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器

    public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
        String factoryClassName = factoryClass.getName();

        try {
            Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");//扫描配置
            ArrayList result = new ArrayList();

            while(urls.hasMoreElements()) {
                URL url = (URL)urls.nextElement();
                Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));//封装成Properties 
                String factoryClassNames = properties.getProperty(factoryClassName);
                result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
            }

            return result;//返回配置名称的列表
        } catch (IOException var8) {
            throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() + "] factories from location [" + "META-INF/spring.factories" + "]", var8);
        }
    }

SpringFactoriesLoader.loadFactoryNames() 扫描所有自动配置jar包类路径下 META‐INF/spring.factories 把扫描到的这些文件的内容包装成properties对象。从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器,将 类路径下 META-INF/spring.factories 里面配置的所有EnableAutoConfiguration的值加入到了容器中;
spring.factories文件中内容如下
在这里插入图片描述

每一个这样的 xxxAutoConfiguration类都是容器中的一个组件,都加入到容器中;用他们来做自动配置;
3)、每一个自动配置类进行自动配置功能;

4)、以HttpEncodingAutoConfiguration(Http编码自动配置)为例解释自动配置原理;
在这里插入图片描述
配置文件的与对应的HttpEncodingProperties属性一一对应
在这里插入图片描述

@Configuration //表示这是一个配置类,与以前编写的配置文件一样,也可以给容器中添加组件

@EnableConfigurationProperties(HttpEncodingProperties.class) //启动指定类的
ConfigurationProperties功能;将配置文件中对应的值和HttpEncodingProperties绑定起来;并把HttpEncodingProperties加入到ioc容器中

@ConditionalOnWebApplication //Spring底层@Conditional注解(Spring注解版),根据不同的条件,如果满足指定的条件,整个配置类里面的配置就会生效; 判断当前应用是否是web应用,如果是,当前配置类生效

@ConditionalOnClass(CharacterEncodingFilter.class) //底层@Conditional注解 判断当前项目有没有这个类CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器;

@ConditionalOnProperty(prefix = “spring.http.encoding”, value = “enabled”, matchIfMissing =true) //底层@Conditional注解 判断配置文件中是否存在某个配置 spring.http.encoding.enabled;如果不存在,matchIfMissing =true 判断也是成立的
//即使我们配置文件中不配置pring.http.encoding.enabled=true,也是默认生效的;

HttpEncodingAutoConfiguration

@Configuration
@EnableConfigurationProperties({HttpEncodingProperties.class})
@ConditionalOnWebApplication
@ConditionalOnClass({CharacterEncodingFilter.class})
@ConditionalOnProperty(
    prefix = "spring.http.encoding",
    value = {"enabled"},
    matchIfMissing = true
)
public class HttpEncodingAutoConfiguration {
 //他已经和SpringBoot的配置文件映射了  
    private final HttpEncodingProperties properties;
//只有一个有参构造器的情况下,参数的值就会从容器中拿
    public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
        this.properties = properties;
    }
   
    @Bean   //给容器中添加一个组件,这个组件的某些值需要从properties中获取
@ConditionalOnMissingBean(CharacterEncodingFilter.class) //判断容器没有这个组件?    
public CharacterEncodingFilter characterEncodingFilter() {    

CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();        
filter.setEncoding(this.properties.getCharset().name());        
filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));        
filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));        
return filter;        
}

根据当前不同的条件判断,决定这个配置类是否生效?一但这个配置类生效;这个配置类就会给容器中添加各种组件;这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的;

5)、所有在配置文件中(application.yml或者application.properties文件)能配置的属性都是在xxxxProperties类中封装者‘;配置文件能配置什么就可以参照某个功
能对应的这个属性类

@ConfigurationProperties(prefix = “spring.http.encoding”) //从配置文件中获取指定的值和bean的属性进行绑定

public class HttpEncodingProperties {
public static final Charset DEFAULT_CHARSET = Charset.forName(“UTF‐8”);

精髓:
1)、SpringBoot启动会加载大量的自动配置类
2)、我们看我们需要的功能有没有SpringBoot默认写好的自动配置类;
3)、我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件有,我们就不需要再来配置了)
4)、给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们就可以在配置文件中指定这些属性的值;

xxxxAutoConfigurartion:自动配置类;给容器中添加组件
xxxxProperties:封装配置文件中相关属性

在这里插入图片描述

自动配置类的通用模式
– xxxAutoConfiguration:自动配置类
– xxxProperties:属性配置类
– yml/properties文件中能配置的值就来源于[属性配置类]

自动配置类必须在一定的条件下才能生效;
我们怎么知道哪些自动配置类生效;
我们可以通过启用 debug=true属性;来让控制台打印自动配置报告,这样我们就可以很方便的知道哪些自动配置类生效;

3 配置文件中debug=true查看详细的自动配置报告

positive 为自动配置上的
negtive为没有配置上的
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

ServerProperties:tomcat的配置

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值