The difference between @ConfigurationProperties and @Value in SpringBoot configuration
1. Basic features
@ConfigurationProperties
- Combine with @Bean to assign values to attributes
- Combine with @PropertySource (only for properties files) to read the specified file
- Combined with @Validation, it supports JSR303 to verify the configuration file value, such as @NotNull@Email, etc.
@Value
- Assign a value to a single attribute
- Supports SpEL expressions on attributes
2. Comparison of the two
@ConfigurationProperties | @Value | |
---|---|---|
Features | Bulk injection of properties in configuration files | Specify one by one |
Loosely bound | stand by | not support |
Game | not support | stand by |
JSR303 data verification | stand by | not support |
Complex type package | stand by | not support |
Note : Loose binding includes camel case, short horizontal writing (-), and underscore writing (_). For example, the official configuration of druid-spring-boot-starter uses short horizontal writing (-) by default. Of course, some blogs on the Internet use camel case writing There is no problem.
空检查
@Null 验证对象是否为null
@NotNull 验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.
Booelan检查
@AssertTrue 验证 Boolean 对象是否为 true
@AssertFalse 验证 Boolean 对象是否为 false
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内
@Length(min=, max=) Validates that the annotated string is between min and max included.
日期检查
@Past 验证 Date 和 Calendar 对象是否在当前时间之前,验证成立的话被注释的元素一定是一个过去的日期
@Future 验证 Date 和 Calendar 对象是否在当前时间之后 ,验证成立的话被注释的元素一定是一个将来的日期
@Pattern 验证 String 对象是否符合正则表达式的规则,被注释的元素符合制定的正则表达式,regexp:正则表达式 flags: 指定 Pattern.Flag 的数组,表示正则表达式的相关选项。
数值检查
建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为”“,Integer为null
@Min 验证 Number 和 String 对象是否大等于指定的值
@Max 验证 Number 和 String 对象是否小等于指定的值
@DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度
@DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度
@Digits 验证 Number 和 String 的构成是否合法
@Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。
@Range(min=, max=) 被指定的元素必须在合适的范围内
@Range(min=10000,max=50000,message=”range.bean.wage”)
@Valid 递归的对关联对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证)
@CreditCardNumber信用卡验证
@Email 验证是否是邮件地址,如果为null,不进行验证,算通过验证。
@ScriptAssert(lang= ,script=, alias=)
@URL(protocol=,host=, port=,regexp=, flags=)
Three, code example
1.@ConfigurationProperties combined with @Component
Typical example: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceWrapper
student:
age: 25
class: mba
lists: a,b,c
mail: [email protected]
maps:
k1: aaa
k2: bbb
k3: ccc
name: zhangsan
score:
english: 95
math: 90
squad-leader: false
@Component
// @PropertySource表示将外部配置文件加载到spring容器中管理
// @PropertySource(value = {"classpath:student.properties"})
@ConfigurationProperties(prefix = "student")
// prefiex表示指定统一前缀,下面就不用再写了
@Validated // ConfigurationProperties形式下支持JSR303校验
public class StudentCP {
private String name;
private Integer age;
// 支持松散绑定,可以将连接符转成驼峰命名
private Boolean squadLeader;
// 当前形式下支持JSR303数据校验,表示此属性值必须是email的格式
@Email
private String mail;
// 支持复杂类型封装对应
private Map<String, Object> maps;
private List<Object> lists;
private Score score;
}
2. Used together with @Configuration and @EnableConfigurationProperties to achieve pluggable configuration
典型示例:org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
/**
* 功能描述:参考 {@link org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration}
*
*/
@Configuration
public class SubSystemAutoConfiguration {
/**
* 加载管理后台配置
*/
@Configuration
@ConditionalOnProperty(prefix = "sub-system", name = "enable", havingValue = "true", matchIfMissing = false)
@EnableConfigurationProperties({
SubSystemProperties.class})
protected static class SubSystemAdminConfiguration{
}
}
@Data
@ConfigurationProperties(prefix = "sub-system")
public class SubSystemProperties implements InitializingBean {
private String policy;
private String finance;
@Override
public void afterPropertiesSet() throws Exception {
}
}
3.@Value usage
Note: The instance object of StudentV must be a spring bean, which can be passed @bean, @Component (including @Controller, @Service, @Configuration, etc.).
@Component
public class StudentV {
// 使用@Value的话只能给属性一一指定映射
@Value("student.name")
private String name;
// @Value形式支持SpEL表达式
@Value("#{13*2}")
// @Value("student.age")
private Integer age;
// @Value("true") // 可直接赋值
// 不能支持松散语法的绑定
@Value("student.squad-leader")
private Boolean squadLeader;
@Value("student.mail")
private String mail;
// 之后的map、list和对象等复杂形式对象@Value无法支持
}
Summary :
- Whether it is @ConfigurationProperties or @Value, if it is to be finally effective, it needs to be managed by spring.
- @value org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
- @ConfigurationProperties org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
Reference:
The difference between @ConfigurationProperties and @Value in SpringBoot configuration The difference between @ConfigurationProperties and @Value in
SpringBoot configuration