1、首先设计一个属性获取类,该类是可以在application.yml中配置属性与功能的核心。
@ConfigurationProperties(prefix="hello")
public class HelloServiceProperties {
private static final String MSG = "hello";
private String msg = MSG;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
2、接下来设计我们需要的bean,这就是一个普通的bean类了
public class HelloService {
private String msg;
public String sayHello(){
System.out.println("sayHello");
return "hello : "+msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
3、系统启动自动注入bean,这个也是自动配置的一个核心模块
@Configuration
@EnableConfigurationProperties(HelloServiceProperties.class)
@ConditionalOnClass(HelloServie.class)
@ConditionalOnProperty(prefix = "hello", value = "enable", matchIfMissing = true)
public class HelloServiceAutoConfiguration {
@Autowired
private HelloServiceProperties helloServiceProperties;
@Bean
@ConditionalOnMissingBean(HelloServie.class)
public HelloServie getHelloServie(){
HelloServie helloServie = new HelloServie();
System.out.println(helloServiceProperties.getMsg());
helloServie.setMsg(helloServiceProperties.getMsg());
return helloServie;
}
}
@EnableConfigurationProperties(HelloServiceProperties.class) 开启HelloServiceProperties.classbean的注解配置与注入
@ConditionalOnProperty(prefix = "hello", value = "enable", matchIfMissing = true)指定的属性是否具有指定的值
@ConditionalOnClass 当类路径下有指定类条件符合
这就实现了一个自动简单的自动配置功能。