配置类+配置属性类+功能类
1.配置类=@Configuration+@ConditionalOnClass,负责将bean注册到容器中。
@Configuration
@ConditionalOnClass(ExampleService.class)
@EnableConfigurationProperties(ExampleServiceProperties.class)
public class ExampleServiceAutoConfigure {
@Autowired
private ExampleServiceProperties properties;
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "yyq.custom.example",value = "enabled",havingValue = "true")
ExampleService exampleService(){
return new ExampleService(properties.getPrefix(),properties.getSuffix());
}
}
2.配置属性ConfigurationProperties:读取application.properties
中的属性
@ConfigurationProperties("yyq.custom.example")
public class ExampleServiceProperties {
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;
}
}
3.定义功能类:类的功能
public class ExampleService {
private String prefix;
private String suffix;
public ExampleService(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
public String wrap(String word){
return prefix+word+suffix;
}
}
4.让SpringBoot管理:通知spring容器导入自己的auto-configuration类。
resources/META-INFO/spring.factories
中添加配置类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=yyq.custom.example.ExampleServiceAutoConfigure
5.maven安装
mvn install
6.使用
在pom
文件中导入后能直接使用了。
<dependency>
<groupId>yyq</groupId>
<artifactId>custom</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>