spirngboot---自动配置原理_有点小白的菜鸟-编程思维

六、自动配置原理

6.1、自动装配原理

以WebMvcProperties为例:

WebMvcProperties.class源码

//从配置文件中获取指定的值和bean的属性进行绑定
@ConfigurationProperties(
    prefix = "spring.mvc"  //前缀
)
public class WebMvcProperties {
    private org.springframework.validation.DefaultMessageCodesResolver.Format messageCodesResolverFormat;
    private final WebMvcProperties.Format format = new WebMvcProperties.Format();
    //就算我们配置文件中不配置类似于dispatchTraceRequest = false这种,它也是默认生效的;
    private boolean dispatchTraceRequest = false;
    private boolean dispatchOptionsRequest = true;
    private boolean ignoreDefaultModelOnRedirect = true;
    private boolean publishRequestHandledEvents = true;
    private boolean throwExceptionIfNoHandlerFound = false;
    private boolean logRequestDetails;
    private boolean logResolvedException = false;
    private String staticPathPattern = "/**";
    private final WebMvcProperties.Async async = new WebMvcProperties.Async();
    private final WebMvcProperties.Servlet servlet = new WebMvcProperties.Servlet();
    private final WebMvcProperties.View view = new WebMvcProperties.View();
    private final WebMvcProperties.Contentnegotiation contentnegotiation = new WebMvcProperties.Contentnegotiation();
    private final WebMvcProperties.Pathmatch pathmatch = new WebMvcProperties.Pathmatch();

这些属性在springboot配置文件application.properties中都可以找到并配置:当输入前缀spring.mvc.时会提示上方源码中的属性:

注意:这里的输入spring.mvc会提示下面这些属性, 原因就是源码中@ConfigurationProperties(
prefix = "spring.mvc"
) 已经绑定了

6.2、配置精髓

1、SpringBoot启动会加载大量的自动配置类

2、我们看我们需要的功能有没有在SpringBoot默认写好的自动配置类当中;

3、我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件存在在其中,我们就不需要再手动配置了)

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

xxxAutoConfigurartion:自动配置类;给容器中添加组件

xxxProperties:封装配置文件中相关属性;

6.3、how知道哪些自动配置类生效?

我们可以通过启用 debug=true属性;来让控制台打印自动配置报告,这样我们就可以很方便的知道哪些自动配置类生效;

#开启springboot的调试类
debug=true

Positive matches:(自动配置类启用的:正匹配)

Negative matches:(没有启动,没有匹配成功的自动配置类:负匹配)

Unconditional classes: (没有条件的类)

版权声明:本文版权归作者所有,遵循 CC 4.0 BY-SA 许可协议, 转载请注明原文链接
https://www.cnblogs.com/malongfeistudy/p/16004375.html