@Configuration //指定这个类是一个配置类 @ConditionalOnXXX //在指定条件成立的情况下自动配置类生效 @AutoConfigureAfter //指定自动配置类的顺序 @Bean //给容器中添加组件 @ConfigurationPropertie(prefix ="xxx") //结合相关xxxProperties类来绑定相关的配置 @EnableConfigurationProperties //让xxxProperties生效, 并加入到容器中 自动配置类要想加载 把需要启动就加载的自动配置类, 配置在: META-INF/spring.factories //比如: org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
<!-- 启动器 --> <dependencies> <!-- 引入自动配置模块 --> <dependency> <groupId>top.binwenhome.starter</groupId> <artifactId>bw-spring-boot-starter-aufoconfigurer</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies>
<dependencies> <!-- 引入spring-boot-starter, 所有starter的基本配置 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> </dependencies>
@ConfigurationProperties(prefix = "hello") public class HelloProperties { private String prefix; private String suffix; public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } }
hello.prefix=xxx
hello.suffix=xxx
public class HelloService { HelloProperties helloProperties; public HelloProperties getHelloProperties() { return helloProperties; } public void setHelloProperties(HelloProperties helloProperties) { this.helloProperties = helloProperties; } public String sayHello(String name) { return helloProperties.getPrefix() + "-" + name + "-" + helloProperties.getSuffix(); } }
@Configuration @ConditionalOnWebApplication //web应用才生效 @EnableConfigurationProperties(HelloProperties.class) public class HelloServiceAutoConfiguration { @Autowired HelloProperties helloProperties; public HelloService helloService() { HelloService service = new HelloService(); service.setHelloProperties(helloProperties); return service; } }
org.springframework.boot.autoconfigure.EnableAutoConfiguration=top.binwenhome.starter.HelloServiceAutoConfiguration
原文:https://www.cnblogs.com/binwenhome/p/12906826.html