项目
xm-common:普通jar项目
- src/main
java
BambooServer.java 需要被实例化的服务类
BambooServerProperties.java 配置信息属性类
BmbooServiceAutoConfiguration.java 自动配置类
resources
META-INF/spring.factories 配置自动配置的属性文件
demo:普通springboot-web项目
需要实例化的服务类
public class BambooServer {
private String name;
public String sayServerName(){
return "I'm " + name + "! ";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
配置信息对应的属性映射类,需要pom中加入spring-boot-starter依赖
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "bamboo")
public class BambooServerProperties {
private static final String NAME = "bamboo_server0";
private String name = NAME;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
自动配置文件
/**
* Author: bamboo
* Time: 2018/11/25/025
* Describe: 自动配置类
* 根据条件判断是否要自动配置,创建Bean
*/
@Configuration
@EnableConfigurationProperties(BambooServerProperties.class)
@ConditionalOnClass(BambooServer.class)//判断BambooServer这个类在类路径中是否存在
@ConditionalOnProperty(prefix = "bamboo",value = "enabled",matchIfMissing = true)
public class BmbooServiceAutoConfiguration {
@Autowired
private BambooServerProperties mistraServiceProperties;
@Bean(name = "bambooServer")
@ConditionalOnMissingBean(BambooServer.class)//当容器中没有这个Bean时(BambooServer)就自动配置这个Bean,Bean的参数来自于BambooServerProperties
public BambooServer mistraService(){
BambooServer mistraService = new BambooServer();
mistraService.setName(mistraServiceProperties.getName());
return mistraService;
}
}
在创建如下路径文件src/main/resources/META-INF/spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.bamboo.common.autoconfigure.bamboo.BmbooServiceAutoConfiguration
必须是自动配置类的全路径
mvn install 该项目
创建一个springboot-mvc项目pom依赖上面的jar
@SpringBootApplication
@RestController
@Import(value = {CorsConfig.class, LogFilter.class}) //跨域,接口访问请求日志
public class DemoApplication {
@Autowired
private BambooServer bmbooService;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@RequestMapping("/")
public Object index(){
return "helll demo"+bmbooService.getName()+DateUtils.getDate();
}
}
http://localhost:8080/则返回当前服务的默认值
在applicaton.yml中加,重启刷新则会更新为如下信息
bamboo:
name: 测试服务
网友评论