提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
在项目中一般读取配置文件最简单的方式是通过@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