SpringBootApplication
SpringBoot的启动类上面,都有一个@SpringBootApplication 注解,该注解主要由以下注解组成:
- EnableAutoConfiguration
- ComponentScan
- SpringBootConfiguration
其中@EnableAutoConfiguration是我们实现自动装配的重要注解,其中最主要的构成是:@Import(AutoConfigurationImportSelector.class),导入了一个AutoConfigurationImportSelector类
该类的selectImports()最终会调用SpringFactoriesLoader的loadSpringFactories方法,而该方法会从META-INF/spring.factories获取配置,从而实现自动装配
ImportSelector
作用是收集需要导入的配置类, 可以通过指定的选择条件来决定哪些类被注册到Spring中
实现自定义的ImportSelector类
1 | public class FormatSelector implements ImportSelector { |
可以仿照SpringBoot的@EnableAutoConfiguration注解,通过自定义的注解,使用@Import导入上面的FormatSelector,如此会将返回的字符串数组中的配置类导入至程序中,实现自动装配
1 | (ElementType.TYPE) |
META-INF/spring.factories
也可直接通过在resources目录下新建META-INF/spring.factories文件,并在文件中写入配置类的全名
1 | =\ |
程序启动时会通过SpringFactoriesLoader类将这些配置自动加载到程序中
Conditional 条件注解
将下面Conditional注解加载Bean上,可以指定Bean在某些条件下才加载,例如:当存在com.alibaba.fastjson.JSON这个类的时候,导入这个Bean
1 | (name = "com.alibaba.fastjson.JSON") |
| Conditions | 描述 |
|---|---|
| @ConditionalOnBean | 在存在某个 bean 的时候 |
| @ConditionalOnMissingBean | 不存在某个 bean 的时候 |
| @ConditionalOnClass | 当前 classpath 可以找到某个类型的类时 |
| @ConditionalOnMissingClass | 当前 classpath 不可以找到某个类型的类时 |
| @ConditionalOnResource | 当前 classpath 是否存在某个资源文件 |
| @ConditionalOnProperty | 当前 jvm 是否包含某个系统属性为某个值 |
| @ConditionalOnWebApplication | 当前 spring context 是否是 web 应用程序 |
获取yml/properties配置
新建一个属性配置类,并添加@ConfigurationProperties注解
1 | (prefix = "yxd.format") |
在配置中添加@EnableConfigurationProperties(FormatProperties.class) 注解,自动注入配置
之后便可在配置文件中写入配置
1 | yxd: |
