@PropertySource 、@ConfigurationProperties 、@Value的使用

三种都是读取配置文件的有关注解

 

@PropertySource 、@ConfigurationProperties用法如下:

wx.properties是resources目录下的配置文件名称,如果有多层,使用斜杆分开即可。classpath:config/wx.properties

 

ma等同于键,需要对应ConfigurationProperties的字首

 

application.yml 格式也一样,属性的命名要跟yml文件命名要一致,也可以写成如下这样:

实体属性命名:homeSign

yml配置命名:home-sign

 

@Value的使用

也可以使用@Value来代替@ConfigurationProperties

AliPayApi是键  SERVER_URL是值

@Value("${AliPayApi.SERVER_URL}")

 

如果是微服务使用nacos来管理的话,在配置类中直接使用@Value,在nacos中配置好比较方便管理

# 支付宝单笔转账配置
AliPayApi:
  SERVER_URL: https:
  APPID: xxxxxxxxxxxx

 

 

当前类引用配置 

    @Value("${ma.money}")
    private Float moneyMin;

注意配置的层级关系,多层使用点号(.) 隔开

 

Nacos动态配置

@RefreshScope
@Configuration
@Data
public class SignatureConfig {

    @Value("${junziqian.service-url}")
    private String serviceUrl;

    @Value("${junziqian.app-key}")
    private String appKey;

    @Value("${junziqian.app-secret}")
    private String appSecret;

    @Value("${junziqian.company-auth-notify-url}")
    private String companyAuthNotifyUrl;

    @Autowired
    private SignatureConfig signatureConfig;

}

 

nacos yml

junziqian:
  service-url: https://xxx.xxx.com
  app-key: xxx
  app-secret: xxx
  company-auth-notify-url: https://xxx.cn/api

 

 

注意:键 值需要空格分离的

还有配置类记得加上他@Component

posted @ 2021-10-20 22:18  安详的苦丁茶  阅读(156)  评论(0编辑  收藏  举报