【串线篇】spring boot自动配置精髓

SpringBoot启动会加载大量的自动配置类即绿色部分

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

比如HttpEncodingAutoConfiguration

、我们再来看这个自动配置类中到底配置了哪些组件;

(只要我们要用的组件有,我们就不需要再来配置了)

、给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。

我们就可以在配置文件中指定这   些属性的值;

其中

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

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

所以说自动配置并不是不用配置,而是不用配置bean了因为EnableAutoConfiguration

会加载大量的自动配置类即绿色部分,

而这些自动配置类就比如HttpEncodingAutoConfiguration会自动给容器添加组件

application.properties文件还是要像上面一样自己写

五、细节

1@Conditional派生注解(Spring注解版原生的@Conditional作用)

作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置配里面的所有内容才生效;

@Conditional扩展注解

作用(判断是否满足当前指定条件)

@ConditionalOnJava

系统的java版本是否符合要求

@ConditionalOnBean

容器中存在指定Bean;

@ConditionalOnMissingBean

容器中不存在指定Bean;

@ConditionalOnExpression

满足SpEL表达式指定

@ConditionalOnClass

系统中有指定的类

@ConditionalOnMissingClass

系统中没有指定的类

@ConditionalOnSingleCandidate

容器中只有一个指定的Bean,或者这个Bean是首选Bean

@ConditionalOnProperty

系统中指定的属性是否有指定的值

@ConditionalOnResource

类路径下是否存在指定资源文件

@ConditionalOnWebApplication

当前是web环境

@ConditionalOnNotWebApplication

当前不是web环境

@ConditionalOnJndi

JNDI存在指定项

自动配置类即绿色

必须在一定的条件下才能生效;

我们怎么知道哪些自动配置类生效;

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

=========================
AUTO‐CONFIGURATION  REPORT
=========================


Positive  matches:(自动配置类启用的)
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
  DispatcherServletAutoConfiguration  matched:
        ‐  @ConditionalOnClass  found  required  class
'org.springframework.web.servlet.DispatcherServlet';  @ConditionalOnMissingClass  did  not  find unwanted  class  (OnClassCondition)
        ‐  @ConditionalOnWebApplication  (required)  found  StandardServletEnvironment
(OnWebApplicationCondition)


Negative  matches:(没有启动,没有匹配成功的自动配置类)
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
  ActiveMQAutoConfiguration:
     Did  not  match:
         ‐  @ConditionalOnClass  did  not  find  required  classes  'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory'  (OnClassCondition)

  AopAutoConfiguration:
     Did  not  match:
         ‐  @ConditionalOnClass  did  not  find  required  classes 'org.aspectj.lang.annotation.Aspect',  'org.aspectj.lang.reflect.Advice'  (OnClassCondition)
原文地址:https://www.cnblogs.com/yanl55555/p/12090018.html