【SpringBoot】使用@ConfigurationProperties/@PropertySource 读取properties/yaml属性,注入字符/数值/日期list/map/对象/

Spring Boot可使用注解的方式将自定义的properties文件映射到实体bean中,比如application.properties文件 或者application.yml。

ConfigurationProperties是一个注解,可以标注在一个Class上,这样Spring Boot会从Environment中获取其属性对应的属性值给其进行注入。

首先看代码项目结构,代码

@Component
@ConfigurationProperties(prefix = "student")
@PropertySource(value = "classpath:application.properties",encoding = "UTF-8")
@Getter
@Setter
@ToString
public class Student {

    private String email ;
    private String name;
    @Value("${student.uname}")
    private String userName;
    @Value("25")
    private int age ;
    private boolean sex ; //true:男  false:女
    private Date birthday ;
    private Map<String,Object> location ;
    private String[] hobbies ;
    private List<String> skills ;

    private Pet pet;

}

public class Pet {
    private String nickName ;//松散写法nick-name
    private String strain ;
}

配置文件application.properties

#通过配置文件修改默认端口(8080)
server.port=8081

#通过配置文件注入对象属性:字符串,数值,日期,list,map,数组,成员对象
student.uname=风雨
student.name=风雨2
student.age=25
student.sex=true
student.birthday=2019/07/24
student.location.province="深圳2
student.location.city='南\n山'
student.location.zone=南\n山
student.hobbies=足球2,篮球f
student.skills=[编程,xue学习]
student.email=624645738@qq.com

student.pet.nickName= wc555
student.pet.strain=strahsq

配置文件yml

server:
  port: 8883
#spring:
#  profiles:
#    active: dev
---
server:
  port: 8884
spring:
  profiles: dev

---  
server:
  port: 8885
spring:
  profiles: test
  
student:
  uname: x   
  name: ${student.user.name2:无名}
  #age: 23
  sex: true
  birthday: 2019/02/12
  location:  {province: "陕222西",city: '西\n安',zone: 莲湖\n区}
      #province: 陕西1
      #city: 西安1
      #zone: 莲湖区1
       #行内写法
  hobbies: 足球2,篮球22    # 行内写法
      
     # - 足球
     # - 篮球
  skills:
      编程333,金融33 # 行内写法
     # - 编程
     # - 金融
  pet: {nick-name: wc555,strain: hsq}
  email: 157468995@qq.com
    #nickName: wc
    #strain: hsq

简单说下properties 和yml 的区别

    application.properties  : k=v,或行内写法(k: v,[Set/List/数组] {map,对象类型的属性},并且 []可省,{}不能省)
    application.yml  :               yaml ain't myarkup language ,不是一个标记文档
                                               1. k:空格v   2.通过垂直对齐 指定层次关系  

                                              3.默认可以不写引号; ""会将其中的转义符进行转义,其他不会

@PropertySource:默认会加载application.properties/application.yml文件中的数据;
    例如@PropertySource(value={"classpath:conf.properties"})加载conf.properties文件中的数据;
    但是,@PropertySource只能加载properties,不能加载yml

--------------------------------------------------------------------------------------------------------------------------

@ConfigurationProperties配置注入的三种方式,配置bean

注意@ConfigurationProperties并没有把当前类注册成为一个Spring的Bean。

  • 配合@Component注解直接进行注入(主要)
@Component
@ConfigurationProperties(prefix = "student")
public class Student {
.....
  • 使用@EnableConfigurationProperties,通常配置在标有@Configuration的类上,当然其他@Component注解的派生类也可以,不过不推荐.(摘取)
@ConfigurationProperties(prefix = "doc")
public class DocumentServerProperties {
    //代码...
}
@EnableConfigurationProperties
@Configuration
public class SomeConfiguration {
    private DocumentServerProperties documentServerProperties
       
    public SomeConfiguration(DocumentServerProperties documentServerProperties) {
        this.documentServerProperties = documentServerProperties;
    }
}
  • 使用@Bean方式在标有@Configuration的类进行注入,这种方式通常可以用在对第三方类进行配置属性注册(摘取)
@Configuration
public class SomeConfiguration {
    
    @Bean
    public DocumentServerProperties documentServerProperties(){
        return new DocumentServerProperties();}
    
    @ConfigurationProperties("demo.third")
    @Bean
    public ThirdComponent thirdComponent(){
        return new ThirdComponent();
    }
}

--------------------------------------------------------------------------------------------------------------------------

@ConfigurationProperties(yml/properties)   和  @Value("xx") 区别

 ConfigurationProperties@Value
注值批量注入单个
松散语法支持不支持
SpEL(Spring表达式语言)不支持    支持
JSR303数据校验    支持不支持
注入复杂类型支持    不支持    

说明:

松散语法 既可以用双引号,也可以用单引号 引号可以省略。

SpEL(Spring表达式语言)

JSR303数据校验 ,利用JSR303规范的实现对DocumentServerProperties属性配置类,添加一些常规验证,比如Null检查、数字校验等操作,

@ConfigurationProperties(prefix = "doc")
@Validated
public class DocumentServerProperties {
    @NotNull // 判断不为空的情况
    private String remoteAddress;
    
    //限制端口只能是80-65536之间
    @Min(80)
    @Max(65536)
    private int port;
    //其他代码
}

:在有些数情况下,我们希望自定义验证器,有两种方式可以进行实现,在此不展开。

ref

阿里云云栖社区  Spring Boot(07)——ConfigurationProperties介绍

 segmentfault  Spring Boot 2.0 @ConfigurationProperties 使用

 

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值