@ConfigurationProperties注解与@Value注解区别

2025-11-11 04:45:17

1、在SpringBoot中,除了使用@ConfigurationProperties注入属性的值,还可以使用Spring的底层注解@Value注入属性的值。

@Component

public class Person {

    @Value("${person.last-name}")

    private String lastName;

    private Integer age;

    private Boolean boss;

    private Date birth;

}

@ConfigurationProperties注解与@Value注解区别

2、这个两个注解都能注入属性的值,那么这两个注解的区别是什么?

@ConfigurationProperties能够批量注入配置文件的属性。

@Value只能一个个指定。

@ConfigurationProperties注解与@Value注解区别

3、@ConfigurationProperties支持松散绑定。

@ConfigurationProperties(prefix = "person"),只需要指定一个前缀,就能绑定有这个前缀的所有属性值。

@ConfigurationProperties注解与@Value注解区别

4、@Value支持SpringEl的语法。@ConfigurationProperties不支持SpringEl的语法。

@ConfigurationProperties注解与@Value注解区别

5、@ConfigurationProperties还支持JSR303进行配置文件值及校验。

@ConfigurationProperties注解与@Value注解区别

6、@Value不支持复杂类型封装注解。

如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value,如果我们转么编写了一个javabean和配置文件进行映射,就直接使用ConfigurationProperties;

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢