本文共 2838 字,大约阅读时间需要 9 分钟。
1、服务类
public class HelloService { private String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String sayHello(){ return "hello" + msg; }}复制代码
2、服务属性配置类
@ConfigurationProperties(prefix = "tutu.hello")public class HelloServiceProperties { private static final String MSG = "world"; private String msg = MSG; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; }}复制代码
3、自动配置类
@Configuration@EnableConfigurationProperties(HelloServiceProperties.class)@ConditionalOnClass(HelloService.class) //判断该类在类路径下是否存在@ConditionalOnProperty(prefix = "tutu", value = "enabled",havingValue = "true",matchIfMissing = true)public class HelloServiceAutoConfiguration { @Autowired private HelloServiceProperties helloServiceProperties; @Bean @ConditionalOnMissingBean(HelloService.class) public HelloService helloService(){ HelloService helloService = new HelloService(); helloService.setMsg(helloServiceProperties.getMsg()); return helloService; }}复制代码
4、注册配置
# 创建resources/META-INF/spring.factories文件org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.test.hello.HelloServiceAutoConfiguration复制代码
5、在使用类中引入该starter,然后在application.properties中修改对象参数,最后利用@Resource引入对象。
大体来看其实没有什么不同,以上方demo为例,ConditionalOnClass和ConditionalOnMissingBean并只是用来提高系统健壮性作用类似于异常处理的地位,如果愿意可以不使用,而ConditionalOnProperty只是用来给予用户控制当前配置类是否生效的开关,如果愿意也可以不使用让他一直处于开启状态,所以去掉上方三个注解并不影响系统的正常使用只是降低了系统健壮性。
但是最为关键的注解是Configuration和ConfigurationProperties和EnableConfigurationProperties,这三个注解在平常项目中都可以被用到,Comfiguration更多用于配制自定义bean,ConfigurationProperties用于配制自定义参数,所以我认为一个自动装配的包和普通jar最大的不同就是自动装配的包拥有默认的参数配置以及拥有自定义参数配置的能力
转载地址:http://fyfvi.baihongyu.com/