老生常谈的SpringBoot约定大于配置是如何实现的?

老生常谈的SpringBoot约定大于配置是如何实现的?

别小看@SpringBootApplication

SpringBoot的启动类头上都会带着@SpringBootApplication注解。先来看看@SpringBootApplication里面有什么。
在这里插入图片描述
包括耳熟能详的@ComponentScan 组件扫描注解和@SpringBootConfiguration 配置类注解。而中间的@EnableAutoConfiguration 正是实现约定大于配置的关键。

@EnableAutoConfiguration

作用:将类路径下 META-INF/spring.factories 里面配置的所有EnableAutoConfiguration的值加入到了容器中。来看下SpringBoot的Jar包中有什么
在这里插入图片描述
可以看到配置了一堆的组件。随便找一个进去看看里面还有什么。
在这里插入图片描述
发现了一个和@EnableAutoConfiguration 及其相似的注解@EnableConfigurationProperties。有了@EnableConfigurationProperties 注解,该类就会在服务启动时,被自动加载进容器中。这就是为什么SpringBoot在启动时,会自动加载大量配置类的原因了。

@Conditional派生注解

最后说下@Conditional派生注解是干嘛用的。
@ConditionalOnClass(xxxxx.class) - 判断项目中是否有这个类
@ConditionalOnMissingBean(xxx.class) - 判断容器中是否有这个组件
@ConditionalOnProperty(prefix = “xxx.xxx”, value = “default”, havingValue = “true”) - 判断配置文件中是否存在某个配置,并赋上默认值
@ConditionalOnWebApplication - 判断当前应用是否是web应用,如果是,当前配置类生效

猜你喜欢

转载自blog.csdn.net/weixin_43776741/article/details/102502308