1 AutoConfiguration的使用之Starter的构建

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引入对象。

2 AutoConfiguration实战细节

2.1 自动装配中各个注解的作用

  • @ConfigurationProperties作用:修饰属性配置类,读取application.properties或application.yml文件中的值然后将值赋予给该类,可以通过创建additional-spring-configuration-metadata.json添加参数正确提示。 { "group": [ { "name": "tutu", "type": "org.test.hello.HelloServiceProperties",//基于贡献该参数的类 "sourceType": "org.test.hello.HelloServiceProperties"//同上 } ], "properties": [ { "name": "tutu.hello.msg", "type": "java.lang.String", "sourceType": "org.test.hello.HelloServiceProperties"//同上 } ], "hints": [ { "name": "tutu.hello.msg", "values": [ { "value": "none",//可以在这些值之外选择,但是编辑器会标红 "description": "Disable DDL handling." } ] } ] } 复制代码
  • @Comfiguration作用:作为@bean的对象来源,但又不同于xml配置的繁琐,基于java代码的对象配置更加便于维护。
  • @EnableConfigurationProperties作用:用来使得ConfigurationProperties修饰的类生效。
  • @ConditionalOnClass作用:判断在当前classpath中是否有指定类,如果有才加载修饰的配置类。
  • @ConditionalOnProperty作用:通过在properties文件中设置havingvlaue对应的参数可以有效控制当前配置类是否生效,也就是用来控制configuration生效。
  • @ConditionalOnMissingBean作用:和@bean配合使用只有在beanfactory中不存在指定类时才创建。

2.2 基于自动装配demo的个人理解

  1. 普通jar包和自动装配stater包有什么不同

大体来看其实没有什么不同,以上方demo为例,ConditionalOnClass和ConditionalOnMissingBean并只是用来提高系统健壮性作用类似于异常处理的地位,如果愿意可以不使用,而ConditionalOnProperty只是用来给予用户控制当前配置类是否生效的开关,如果愿意也可以不使用让他一直处于开启状态,所以去掉上方三个注解并不影响系统的正常使用只是降低了系统健壮性。

但是最为关键的注解是Configuration和ConfigurationProperties和EnableConfigurationProperties,这三个注解在平常项目中都可以被用到,Comfiguration更多用于配制自定义bean,ConfigurationProperties用于配制自定义参数,所以我认为一个自动装配的包和普通jar最大的不同就是自动装配的包拥有默认的参数配置以及拥有自定义参数配置的能力