Spring Boot几个注解的区别,如@ConfigurationProperties和@Value等

Spring Boot几个注解的区别,如@ConfigurationProperties和@Value等

@ConfigurationProperties和@Value的区别

@ConfigurationProperties @Value
功能 批量注入值 一个一个的指定
松散绑定(驼峰、下划线等转换) 支持 不支持
SpEL 不支持 支持
JSR303校验 支持 不支持
复杂类型封装 支持 不支持

JSR303校验

@Component
@ConfigurationProperties(prefix = "user")
@Validated
public class User {

    @Email
    private String name;
    private int age;
    private int sex;
    private Map<String, Object> maps;
    @NotNull
    private Pet pets;

报错信息如下:

Property: user.name
Value: renoside
Origin: "user.name" from property source "systemProperties"
Reason: 不是一个合法的电子邮件地址

注:使用@Value注入properties文件中的信息时,开启验证也不会报错

@PropertySource

@ConfigurationProperties是从全局配置文件中拉取信息,而@PropertySource可以指定加载的配置文件

示例:

@Component
//@Validated
@ConfigurationProperties(prefix = "user")
@PropertySource(value = "classpath:user.properties")
public class User {

//    @Email
    private String name;
    private int age;
    private int sex;
    private Map<String, Object> maps;
//    @NotNull
    private Pet pets;

@ImportResource

@ImportResource的作用是导入Spring的配置文件,让配置文件中的内容生效。在Spring Boot中,基于xml的配置是无法自动生效的,必须使用@ImportResource(locations = {"", "", ...})使xml配置生效,可以写在Spring Boot项目的主程序类(主入口类)上

但是,这么写是很麻烦的,Spring Boot官方推荐的做法是使用全注解的方式,即写专门的配置类,在配置类中使用@Bean的方式注入组件,也就是Spring中注解注入组件的方式