SpringBoot自动配置讲解
首先我们要知道SpringBoot 在启动时会去依赖的starter包中寻找 resources/META-INF/spring.factories 文件,然后根据文件中配置的Jar包去扫描项目所依赖的Jar包,然后,根据 spring.factories 配置加载AutoConfigure类,最后,根据 @Conditional 注解的条件,进行自动配置并将Bean注入Spring Context 上下文当中。
我们大致了解一下@Conditional注解作用
@Conditional扩展注解 | 作用(判断是否满足当前指定条件) |
---|---|
@ConditionalOnJava | 系统的java版本是否符合要求 |
@ConditionalOnBean | 容器中存在的指定Bean |
@ConditionalOnMissingBean | 容器中不存在的指定Bean |
@ConditionalOnExpression | 满足SpEl表达式指定 |
@ConditionalOnClass | 系统中有指定的类 |
@ConditionalOnMissingClass | 系统中没有指定的类 |
@ConditionalOnSingleCandidate | 容器中只有一个指定的Bean,或者这个Bean是首选的Bean |
@ConditionalOnProperty | 系统中指定的属性是否有指定的值 |
@ConditionalOnResource | 类路径下是否存在指定的资源文件 |
现在我们可以自己编写一个starter感受一下
1.编写一个Service类
public class StarterService {
private String config;
public StarterService(String config) {
this.config = config;
}
public String[] split(String separatorChar) {
return StringUtils.split(this.config, separatorChar);
}
}
2.编写一个配置类
@ConfigurationProperties("example.service")
public class StarterServiceProperties {
private String config;
public void setConfig(String config) {
this.config = config;
}
public String getConfig() {
return config;
}
}
3.编写一个自动配置类
@Configuration
@ConditionalOnClass(StarterService.class)
//开启配置参数
@EnableConfigurationProperties(StarterServiceProperties.class)
public class StarterAutoConfigure {
@Autowired
private StarterServiceProperties properties;
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "example.service", value = "enabled", havingValue = "true")
StarterService starterService (){
return new StarterService(properties.getConfig());
}
}
4.maven打包到本地仓库
mvn install
到此一个自定义的starter就完成了,现在我们将他引入项目中使用测试
1.引入我们自定义的starter
<dependency>
<groupId>com.example</groupId>
<artifactId>myspringboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
2.配置文件 (这里的debug=true)是开debug模式,springboot就会打印自动加载的类,那些加载了那些没加载
server:
port: 8086
example:
service:
enabled: true
config: abc-des-dde,SSS-DRS-RE,SDR-SDFR-XXX
debug: true
3.测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyspringbootApplication.class)
public class ParentTest {
@Test
public void test4(){
String[] split = starterService.split(",");
Arrays.asList(split).forEach(System.out::println);
}
}
可以看到这里 positive matches是加载的了自动加载类
版权声明:本文为weixin_44012722原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
发表回复