SpringBoot自动装配

85 阅读5分钟

uVmnsIuHhK.jpg

在使用SpringBoot的过程中,想必最爽的就是省却了以前ssm年代的大量配置,且集成tomcat,易上手,操作易,那么自动配置是如何做的呢?

配置文件到底能写什么?怎么写?和以往的下xml配置文件有什么关联? 想要解答这个问题,恐怕就要去了解SpringBoot为我们自动做了什么事情,了解它是如何做的,我们自然就知道要如何修改了。 本编中出现的源码基于1.5.9.RELEASE 高版本可能不同,但是万变不离其宗。

自动配置原理

  • SpringBoot启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration,可以从这里入手,探索这个注解做了什么事情。
  • 点开源码发现里面通过@Import 导入了EnableAutoConfigurationImportSelector组件,那么这个是干什么的呢,接着点进去查看,点击父类AutoConfigurationImportSelector,查看selectImports()方法List configurations = getCandidateConfigurations(annotationMetadata, attributes); 获取候选的配置。
  • SpringFactoriesLoader.loadFactoryNames()扫描所有jar包类路径下 META‐INF/spring.factories,把扫描到的这些文件的内容包装成properties对象,从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器中,如下图
org.springframework.boot.autoconfigure.EnableAutoConfiguration,\
org.springframework.bootautoconfigure,admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration
  • 每一个这样的 xxxAutoConfiguration类都是容器中的一个组件,都加入到容器中;用他们来做自动配置
//表示这是一个配置类,和以前编写的配置文件一样,也可以给容器中添加组件
@Configuration 
//启动指定类的ConfigurationProperties功能;将配置文件中对应的值和HttpEncodingProperties绑定起来;
//并把HttpEncodingProperties加入到ioc容器中
@EnableConfigurationProperties(HttpEncodingProperties.class) 
//Spring底层@Conditional注解( Spring注解版),根据不同的条件,如果满足指定的条件,
//整个配置类里面的配置就会生效;判断当前应用是否是web应用,如果是,当前配置类生效
@ConditionalOnWebApplication 
//判断当前项目有没有这个类CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器;
@ConditionalOnClass(CharacterEncodingFilter.class) 
//判断配置文件中是否存在某个配置 spring.http.encoding.enabled;如果不存在,判断也是成立的
//即使我们配置文件中不配置spring.http.encoding.enabled=true,也是默认生效的
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchifMissing true) 
public class HttpEncodingAutoConfiguration {
    //已经和springBoot的配置文件映射了
    private final HttpEncodingProperties properties;
    
    //只有一个有参构造器的情况下,参数的值就会从容器中拿
    public HttpEncodingAutoConfiguration(HttpEncodingProperties properties){
        this.properties = properties;
    }

//给容器中添加一个组件,这个组件的某些值需要从properties中获取
@Bean
//判断容器没有这个组件?
@Conditional0nMissingBean(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;
 }
  • SpringBoot启动会加载大量的自动配置类

  • 我们看我们需要的功能有没有SpringBoot默认写好的自动配置类;

  • 我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件有,我们就不需要再来配置了)

  • 给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们就可以在配置文件中指定这些属性的值;

  • 在application.yml中配置 debug: true 来打印bean的装载过程

  • @Conditional扩展

@Conditional扩展注解作用(判断是否满足当前指定条件)
@ConditionalOnJava系统的java版本是否符合要求
@ConditionalOnBean容器中存在指定Bean
@ConditionalOnMissingBean容器中不存在指定Bean
@ConditionalOnExpression满足指定SpEL表达式
@ConditionalOnClass系统中有指定的类
@ConditionalOnMissingClass系统中没有指定的类
@ConditionalOnSingleCandidate容器中只有一个指定的Bean,或者这个Bean是首选Bean
@ConditionalOnProperty系统中指定的属性是否有指定的值
@ConditionalOnResource类路径下是否存在指定资源文件
@ConditionalOnWebApplication当前是web环境
@ConditionalOnNotWebApplication当前不是web环境
@ConditionalOnJndiJNDI存在指定项

SpringMVC自动配置

  • Spring Boot 自动配置好了SpringMVC,自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染),其中ContentNegotiatingViewResolver是组合所有的视图解析器的
  • HttpMessageConverter:SpringMVC用来转换Http请求和响应的;User---Json;
  • HttpMessageConverters 是从容器中确定;获取所有的HttpMessageConverter;
  • 自己给容器中添加HttpMessageConverter,只需要将自己的组件注册容器中(@Bean,@Component);
  • 经典的将返回值交给fastjson解析。
//引入Fastjson解析json,不使用默认的jackson 
//必须在pom.xml引入fastjson的jar包,并且版必须大于1.2.10 
@Bean 
public HttpMessageConverter fastJsonHttpMessageConverters() { 
    logger.info("fastjson。。HTTP messageConverter start..."); 

    //1、定义一个convert转换消息的对象 
    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

    //2、添加fastjson的配置信息 
    FastJsonConfig fastJsonConfig = new FastJsonConfig(); 
    SerializerFeature[] serializerFeatures = new SerializerFeature[]{ 
    // 输出key是包含双引号 
     SerializerFeature.QuoteFieldNames, 
    // 是否输出为null的字段,若为null 则显示该字段 
     SerializerFeature.WriteMapNullValue, 
    // 数值字段如果为null,则输出为0 
     SerializerFeature.WriteNullNumberAsZero, 
    // List字段如果为null,输出为[],而非null 
    SerializerFeature.WriteNullListAsEmpty, 
    // 字符类型字段如果为null,输出为"",而非null 
    SerializerFeature.WriteNullStringAsEmpty, 
    // Boolean字段如果为null,输出为false,而非null 
    SerializerFeature.WriteNullBooleanAsFalse, 
    // Date的日期转换器 SerializerFeature.WriteDateUseDateFormat,
    // 循环引用 SerializerFeature.DisableCircularReferenceDetect, 
    }; 
    
    fastJsonConfig.setSerializerFeatures(serializerFeatures); 
    fastJsonConfig.setCharset(Charset.forName("UTF-8")); 
    
    //3、在convert中添加配置信息 
    fastConverter.setFastJsonConfig(fastJsonConfig); 
    return fastConverter; 
}

拓展Spring MVC:

  • 在spring-boot中的做法是(可以参照官方文档):
  • 编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc;既保留了所有的自动配置,也能用我们扩展的配置;
//使用webMvcConfigurerAdapter可以来扩展SpringMVC的功能@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    // super.addViewControllers(registry);
    //浏览器发送 /student 请求来到 success
    registry.addViewController("/student").setViewName( "success");
    }
}
  • 那么为什么我们自己写了一个WebMvcConfigurerAdapter就生效了呢?
    • WebMvcAutoConfiguration是SpringMVC的自动配置类
    • 在做其他自动配置时会导入@Import(EnableWebMvcConfiguration.class),会从容器中获取所有的WebMvcConfigurer
    • 容器中所有的WebMvcConfigurer都会一起起作用
    • 我们的配置类也会被调用;所以:效果:SpringMVC的自动配置和我们的扩展配置都会起作用;