参考:https://www.cnblogs.com/jimoer/p/11374229.html
理解@ConfigurationProperties
在编写项目代码时,我们要求更灵活的配置,更好的模块化整合。在 Spring Boot 项目中,为满足以上要求,我们将大量的参数配置在 application.properties 或 application.yml 文件中,通过 @ConfigurationProperties 注解,我们可以方便的获取这些参数值
使用@ConfigurationProperties
在application.properties
文件中创建参数:
myapp.mail.enabled=true
myapp.mail.default-subject=This is a Test
我们可以使用@Value
注解或者使用Spring Environment bean访问这些属性,但是这种注入配置方式有时显得很笨重,对于多个同样前缀的变量采用@Value的注解方式,很麻烦。
此时,我们使用更安全的方式 (@ConfigurationProperties(prefix = ' ' )
)来获取这些属性:
@Data
@ConfigurationProperties(prefix = 'myapp.mail')
public class MailMouldeProperties{
private Boolean enabled;
private String defaultSubject;
}
激活@ConfigurationProperties
对于Springboot, 创建一个MailModuleProperties类型的Bean,我们可以通过下面几种方式将其添加到应用上下文中。
首先,我们可以通过添加@Component
注解让 Component Scan扫描到
@Component
@ConfigurationProperties(prefix="myapp.mail")
class MailModuleProperties{
//....
}
很显然,只有当类所在的包被Spring的@Component
注解扫描到才会生效,默认情况下,该注解会扫描在主应用类下的所有包结构。
我们也可以通过Spring的Java Configuration特性实现同样的效果。
@Configuration
class PropertiesConfig{
@Bean
public MailModuleProperties mailModuleProperties(){
return new MailModuleProperties();
}
}
只要 MailModuleConfiguration 类被 Spring Boot 应用扫描到,我们就可以在应用上下文中访问 MailModuleProperties bean
我们还可以使用 @EnableConfigurationProperties
注解让我们的类被 Spring Boot 所知道,在该注解中其实是用了@Import(EnableConfigurationPropertiesImportSelector.class)
实现,大家可以看一下
@Configuration
@EnableConfigurationProperties(MailModuleProperties.class)
class PropertiesConfig{
}
激活一个 @ConfigurationProperties 类的最佳方式是什么?
所有上述方法都同样有效。然而,我建议模块化你的应用程序,并让每个模块提供自己的@ConfigurationProperties 类,只提供它需要的属性,就像我们在上面的代码中对邮件模块所做的那样。这使得在不影响其他模块的情况下重构一个模块中的属性变得容易。
因此,我不建议在应用程序类本身上使用 @EnableConfigurationProperties,如许多其他教程中所示,是在特定于模块的 @Configuration 类上使用@EnableConfigurationProperties,该类也可以利用包私有的可见性对应用程序的其余部分隐藏属性。