一、maven依赖
1 2 3 4 5 6
| <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </dependency> </dependencies>
|
二、设置配置文件相应类目的前缀
1 2 3 4 5
| @ConfigurationProperties("example.service") public class ExampleServiceProperties { private String prefix; private String suffix;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @Configuration @ConditionalOnClass(ExampleService.class) @EnableConfigurationProperties(ExampleServiceProperties.class) public class ExampleAutoConfigure { @Autowired private ExampleServiceProperties properties; @Bean @ConditionalOnMissingBean @ConditionalOnProperty(prefix = "example.service",value = "enabled",havingValue = "true") ExampleService exampleService (){ return new ExampleService(properties.getPrefix(),properties.getSuffix()); } }
|
1
| org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.autocinfigure.ExampleAutoConfigure
|
五、原理
- Spring Boot在启动时扫描项目所依赖的JAR包,寻找包含spring.factories文件的JAR包
- 根据spring.factories配置加载AutoConfigure类
- 根据 @Conditional注解的条件,进行自动配置并将Bean注入Spring Context
六、鸣谢
http://www.jianshu.com/p/45538b44e04e