美文网首页
简述 Spring Boot 自动配置魔法

简述 Spring Boot 自动配置魔法

作者: 编程人生 | 来源:发表于2023-04-14 14:58 被阅读0次

一. 自动配置的魔法

Spring Boot auto-configuration magic comes from spring-boot-autoconfigure-{version}.jar

自动装配的魔法来自 spring-boot-autoconfigure-(version).jar

spring.factories  文件包括了 需要的所有spring -boot - autoconfigure-{version}.jar

二.与自动配置有关的一些注解

 @ConditionalOnClass({Servlet.class ,DispatherServlet.class ,WebMvcConfigurerAdapter.class})

        英文 :This auto-configuration is enabled if any of the mentioned class are in the classpath.

        中文: 这个自动配置生效条件是如果被提到的类在classpath中.

@ConditionalOnMissingBean(WebMvcConfigurationSuppot.class):

          英文:This auto-configurationis enabled only if application does not explicity delare a bean of the WebMvcConfigurationSuppot.class

           中文:这个自动配置生效条件是如果没有显示声明WebMvcConfigurationSuppot bean 

@AutoconfigureOrder(Ordered.HIGHEST_PRECEDENCE+10)

            英文: This specifies the precedence of this specific auto-configuration

            中文 :这个指明了自动配置类的优先级.

举例 :来看下面代码片段

@ConditionalOnBean(ViewResolver.class) : 

注解含义: 如果在classpath 中有 viewRresolver 这个类. 则创建 一个 bean  ContentNegotiatingViewResolver 

@ConditionalOnMissingBean(name = "viewResolver", value=ContentNegotiationgViewResolver.class):

注解含义: 

英文 :Create this bean if there are no explicity delcared beans of the name viewResolver and of type ContentNegotiatingViewResolver.class

中文: 如果没有显示声明 名字是 viewResolver  和  类型是 ContentNegotiatingViewResolver,则创建这个bean

总结: summarize 

        To summarize ,all the auto-configuration logic is executed at the start of a Spring Boot application . if a specific class(from a specific dependency or starter project) is available on the classpath , then the autoconfiguration classes are executed .This auto-configurationclasses look at what beans are already configured .  Based on the existing beans ,they enable the creation of the default beans .

        总结, 所有自动装配的逻辑在 spring boot application 应用开始时执行的. 如果一个指定的类在 classpath中有效,  这些自动装配的类被执行. 自动装配的类查看这些已经配置的哪些bean. 基于这些beans ,它们能创造默认的bean.

相关文章

网友评论

      本文标题:简述 Spring Boot 自动配置魔法

      本文链接:https://www.haomeiwen.com/subject/ajctjdtx.html