test-spring-boot-autoconfigure
pom引入
<parent>
<!-- 导入spring boot的web支持 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
配置文件类
@ConfigurationProperties(prefix = "test.hello")
public class HelloProperties {
private String suffix;
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
}
服务类
public class HelloService {
HelloProperties helloProperties;
public String sayHello(String name) {
return "Hello " + name + "," + helloProperties.getSuffix();
}
public HelloProperties getHelloProperties() {
return helloProperties;
}
public void setHelloProperties(HelloProperties helloProperties) {
this.helloProperties = helloProperties;
}
}
注册类
/**
* web应用才生效
*/
@ConditionalOnWebApplication
/**
* 让属性文件生效
*/
@EnableConfigurationProperties(HelloProperties.class)
/***
* 声明是一个配置类
*/
@Slf4j
@Configuration
public class HelloServiceAutoConfiguration {
@Autowired
private HelloProperties helloProperties;
@Bean
public HelloService helloService() {
log.info("开始注册HelloService Bean");
HelloService helloService = new HelloService();
helloService.setHelloProperties(helloProperties);
return helloService;
}
}
resources/META-INF下创建文件spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.test.autoconfig.HelloServiceAutoConfiguration
test-spring-boot-starter
为空,pom.xml引入
<dependency>
<groupId>com.test</groupId>
<artifactId>test-spring-boot-autoconfigure</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
配置类
测试在SpringBoot项目中,pom.xml引入自动配置项目
<dependency>
<groupId>com.test</groupId>
<artifactId>test-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
配置
test.hello.suffix=早上好
注入HelloService,即可使用。
@Autowired
private HelloService helloService;
参考 https://www.cnblogs.com/niumoo/p/11775009.html