首先需要在创建的springboot项目的pom中,加入Starter的自动化配置类:
<!-- starter的自动化配置类 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>
创建一个HelloProperties类用于接收application.properties中注入的值
//匹配test.开头的文件属性,自动装配
@ConfigurationProperties(prefix = "test")
public class HelloProperties {
private static final String DEFAULT_NAME = "浪里白条";
private static final String DEFAULT_MSG = "黑旋风";
private String name = DEFAULT_NAME;
private String msg = DEFAULT_MSG;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
定义HelloService:
public class HelloService {
private String msg;
private String name;
public String sayHello() {
return name + " say " + msg + " !";
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
定义自动化配置类:
//表明这是配置类
@Configuration
//使之前配置的 @ConfigurationProperties 生效,让配置的属性成功的进入 Bean 中
@EnableConfigurationProperties(HelloProperties.class)
//表示当项目当前 classpath 下存在 HelloService 时,后面的配置才生效
@ConditionalOnClass(HelloService.class)
public class HelloServiceAutoConfiguration {
@Autowired
HelloProperties helloProperties;
@Bean
HelloService helloService(){
HelloService helloService = new HelloService();
helloService.setName(helloProperties.getName());
helloService.setMsg(helloProperties.getMsg());
return helloService;
}
}
在resources目录下创建名为META-INF的文件夹,在文件夹中创建名为spring.factories的文件:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.test_start.HelloServiceAutoConfiguration
在idea中使用maven的install进行打包,讲打包的jar包复制到另外的springboot项目中进行引用。
新建测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestDemo {
@Autowired
HelloService helloService;
@Test
public void contextLoads() {
System.out.println(helloService.sayHello());
}
}
application.properties中设置新值。
运行测试类:
Starter定义车成功!