@ConfigurationProperties的多级使用

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

在项目中一般读取配置文件最简单的方式是通过@Value注解直接读取,但是如果要读取大量的配置文件信息时,使用@Value注解就不合适了(可读性和维护性太差),因此改用@ConfigurationProperties。

代码示例

1.application.yml

api:
  vehicle:
    username: admin
    password: 123456
    grantType: password
    get-token:
      url: https://blog.csdn.net/weixin_46425661
      query: spm=1000.2115.3001.5343
      header:
        AuthParam: authority
        AuthValue: aaabbbccc==

2.配置类

代码如下(示例):

@Component
@ConfigurationProperties(prefix = "api.vehicle")
@Data
public class VehicleBaseConfig {
    private String username;
    private String password;
    private String grantType;

    @Data
    @ConfigurationProperties(prefix = "api.vehicle.get-token")
    @Component
    public static class GetTokenConfig{
        private String url;
        private String query;
        @Data
        @ConfigurationProperties(prefix = "api.vehicle.get-token.header")
        @Component
        public static class HeaderConfig{
            private String AuthParam;
            private String AuthValue;
        }
    }
}

3.服务类

    @Component
    public class TestService{
        @Autowired
        private VehicleBaseConfig vehicleBaseConfig;
        @Autowired
        private VehicleBaseConfig.GetTokenConfig getTokenConfig;
        @Autowired
        private VehicleBaseConfig.GetTokenConfig.HeaderConfig headerConfig;
        public void test() {
            System.out.println(vehicleBaseConfig.toString());
            System.out.println(getTokenConfig.toString());
            System.out.println(headerConfig.toString());
        }
    }

4.输出台打印

VehicleBaseConfig(username=admin, password=123456, grantType=password)
VehicleBaseConfig.GetTokenConfig(url=https://blog.csdn.net/weixin_46425661, query=spm=1000.2115.3001.5343)
VehicleBaseConfig.GetTokenConfig.HeaderConfig(AuthParam=authority, AuthValue=aaabbbccc==)

参考文章:https://blog.csdn.net/rain_web/article/details/105443423

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值