- 导入spring的autoconfigure的starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
-
写一个默认的配置 xxxProperties 类。。这个类使用@ConfigurationProperties 引入外部的配置文件,并且设置自己的默认属性值 -
写一个你要注入容器的xxxService类。 (xxxProperteis 和 xxxService 属性名字是一样的,xxxProperties相当于 xxxService的默认属性值) -
写一个xxxServiceAutoConfiguration类,这个类使用@EnableConfigurationProperties 开启上面的xxxProperties 类的属性注入,这样xxxProperties 类的对象就被注入到容器中,然后注入一个xxxService的Bean,将xxxProperties的值赋值给xxxService。。通过@ConditionalOnClass判断用户是否使用了xxxService,如果使用了就自动注入 -
@SpringBootApplication 下的@EnableAutoConfiguration 表示会启用Spring应用程序上下文自动配置,该注解会自动导入一个名为AutoConfigurationImportSelector 类,而这个类回去读取一个名为spring.factories文件,,这个spring.factories文件中则定义了需要加载的自动化配置类,所以我们也需要自定义一个starter。。首先在resources下创建 META-INF 文件夹,然后在文件夹中创建一个名为spring.factories文件,文件内容如下
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.cj.HelloServiceAutoConfiguration
- 本地安装 使用maven的 install 命令
- 使用starter,,在别的工程中导入这个安装工程的坐标
<dependency>
<groupId>com.cj</groupId>
<artifactId>mystarter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
代码:
@ConfigurationProperties(prefix = "user")
public class HelloProperties {
private static final String DEFAULT_USERNAME="waterkid";
private static final String DEFAULT_MSG ="xxx";
private String username = DEFAULT_USERNAME;
private String msg = DEFAULT_MSG;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
public class HelloService {
private String username;
private String msg;
@Override
public String toString() {
return "HelloService{" +
"username='" + username + '\'' +
", msg='" + msg + '\'' +
'}';
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
@Configuration
@ConditionalOnClass(HelloService.class)
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {
@Autowired
HelloProperties helloProperties;
@Bean
HelloService helloService(){
HelloService helloService = new HelloService();
helloService.setUsername(helloProperties.getUsername());
helloService.setMsg(helloProperties.getMsg());
return helloService;
}
}
在另一个工程中测试
@SpringBootApplication
public class Demo {
static HelloService helloService;
public static void main(String[] args) {
SpringApplication.run(Demo.class,args);
System.out.println(helloService);
}
@Autowired
public void setHelloService(HelloService helloService) {
Demo.helloService = helloService;
}
}
|