Springboot - @ConfigurationProperties再次入坑^_^

    平时在application.yml中配置并读取参数的时候,@ConfigurationProperties这个注解总是必不可少的,例如:

adaptor:
    request:
        queueSize: 1000
    imp:
        hotReloadDelay: 60
    threadPool:
        corePoolSize: 20
        maximumPoolSize: 60
        keepAliveTime: 60
        queueSize: 1000
    alarmSending:
        threadPool:
            corePoolSize: 5
            maximumPoolSize: 20
            queueSize: 2000
            keepAliveTime: 60
        timeout: 500
        retry:
            MessageRetry: true
            PayloadExpirationTime: 10
            RetryInterval: 5
            PayloadDiscardDirectory: /home/ec2-user/daopinz/discard/

    代码读取的地方是这样的:

@Value("${adaptor.alarmSending.retry.MessageRetry}")
private boolean messageRetry = false;
@Value("${adaptor.alarmSending.retry.PayloadExpirationTime}")
private int payloadExpirationTime = 5;
@Value("${adaptor.alarmSending.retry.RetryInterval}")
private int retryInterval = 5;
@Value("${adaptor.alarmSending.retry.PayloadDiscardDirectory}")
private String PayloadDiscardDirectory;

    这里有一个小问题;${adaptor.alarmSending.retry.PayloadDiscardDirectory}这里写的是绝对路径,读取会有问题哦~

    那么换个方式呗,@ConfigurationProperties注解就可以”闪亮登场“咯,


@Service
@ConfigurationProperties(prefix = "adaptor.alarmSending.retry")

... ...

private String payloadDiscardDirectory;
public String getPayloadDiscardDirectory(){return payloadDiscardDirectory;}
public void setPayloadDiscardDirectory(String payloadDiscardDirectory){
	this.payloadDiscardDirectory = payloadDiscardDirectory;
}

   @ConfigurationProperties是让开发人员比较容易地将整个文件映射成一个对象 ;

   基本用法非常简单:我们为每个要捕获的外部属性提供一个带有字段的类。请注意以下几点:

  • 前缀定义了哪些外部属性将绑定到类的字段上
  • 根据 Spring Boot 宽松的绑定规则,类的属性名称必须与外部属性的名称匹配
  • 我们可以简单地用一个值初始化一个字段来定义一个默认值
  • 类本身可以是包私有的
  • 类的字段必须有公共 setter 方法

    是不是也挺简单的呢,写个demo自己试试吧^_^;;

posted @ 2022-01-27 18:35  zhangdaopin  阅读(111)  评论(0编辑  收藏  举报