我们知道导入配置有两种,一种是@Value,一种是@ConfigurationProperties,将对应的类标记为Component即可导入。但是被注解标识的类创建Bean有一个前提,只对启动类所在的包路径下的所有带有@Component等注解的类才会创建Bean。如果我们封装的是一个公共依赖库,这些配置是不会自动导入到我们的程序中的。这时需要AutoConfigure来实现。
1、定义一个类存储配置信息,类的成员变量大家自行定义,如果不想生成get和set方法,可以使用Lombok的Getter和Setter注解。
@Setter
@Getter
@Component
@ConfigurationProperties(prefix = "app")
public class MyAppProperties {
private Boolean testFlag;
private String testName;
}
2、编写自动装配类,用于导入配置并生成Bean实例。
@AutoConfiguration
@ConditionalOnClass({MyAppProperties.class})
@EnableConfigurationProperties({MyAppProperties.class})
public class MyAppPropertiesAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = {"myAppProperties"})
public MyAppProperties myAppProperties() {
return new MyAppProperties();
}
}
其中关键点有两个:一是@AutoConfigure注解,用于自动导入配置,二是@EnableConfigurationProperties注解,用于标记自动导入配置到MyAppProperties实