配置文件读取到类属性上

今天直接给我人整无语了。
先说说如何把配置文件读取到类属性上吧。
首先第一步编写配置文件

cos:
  secretId: "xxx"
  secretKey: "xxx"
  appId: "xxx"
  bucketName: "xxx"
  region: "xxx"
  url: "xxx"

再把前缀绑定到想要注入值的类上去

import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "cos")
@Data
@ToString
public class COSConfig {
    private String secretId;
    private String secretKey;
    private String appId;
    private String bucketName;
    private String region;
}

@ConfigurationProperties(prefix = “cos”):绑定配置文件的指定前缀。
@Data:Lombok添加getter和setter方法,没有的话注入不进去。

是不是发现很简单!生活竟然如此美好!接下来我要开始我的窒息操作了!
我写了一个test去测试是否注入成功。

@Test
    public void testPro(){
    System.out.println(secretId);
    System.out.println(secretKey);
    System.out.println(appId);
}

结果
在这里插入图片描述
我还觉得奇怪怎么会没注入进去呢于是上网找资料怒干两个小时一无所获。第二天在即将崩溃的边缘悟道了。
springboot都没运行起来那个容器都还没有你要谁给你注入值啊救命啊!
实在想测也加个@RunWith让容器先跑起来好吧。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值