La diferencia entre @ConfigurationProperties y @Value en la configuración de SpringBoot

La diferencia entre @ConfigurationProperties y @Value en la configuración de SpringBoot

1. Funciones básicas

@Propiedades de configuración

  • Combinar con @Bean para asignar valores a los atributos
  • Combine con @PropertySource (solo para archivos de propiedades) para leer el archivo especificado
  • Combinado con @Validation, admite JSR303 para verificar el valor del archivo de configuración, como @ NotNull @ Email, etc.

@Valor

  • Asignar un valor a un solo atributo
  • Admite expresiones SpEL sobre atributos

2. Comparación de los dos

@Propiedades de configuración @Valor
Caracteristicas Inyección masiva de propiedades en archivos de configuración Especificar uno por uno
Débilmente unida colocarse no apoyo
Juego no apoyo colocarse
Verificación de datos JSR303 colocarse no apoyo
Paquete de tipo complejo colocarse no apoyo

Nota : Las encuadernaciones sueltas incluyen mayúsculas y minúsculas, guiones cortos (-) y guiones bajos (_). Por ejemplo, la configuración oficial de druid-spring-boot-starter utiliza guiones cortos (-) de forma predeterminada. Por supuesto, algunos blogs en el caso camel del uso de Internet No hay problema.

空检查 
@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=)

Tres, ejemplo de código

1. @ ConfigurationProperties combinado con @Component

Ejemplo típico: 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. Se utiliza junto con @Configuration y @EnableConfigurationProperties para lograr una configuración conectable

典型 示例 : 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. @ Valor de uso

Nota: El objeto de instancia de StudentV debe ser un bean de primavera, que puede pasarse a @bean, @Component (incluido @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无法支持

}

Resumen :

  • Ya sea @ConfigurationProperties o @Value, para que finalmente sea efectivo, debe administrarse antes de la primavera.
  • @value org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
  • @ConfigurationProperties org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor

Referencia:
La diferencia entre @ConfigurationProperties y @Value en la configuración de SpringBoot La diferencia entre @ConfigurationProperties y @Value en la
configuración de SpringBoot

Supongo que te gusta

Origin blog.csdn.net/ory001/article/details/112772747
Recomendado
Clasificación