我有个配置设计相关的需求 大概是这样
可以理解为提供给一个工厂方法的配置文件
spring: ... vendor: proto: // 原型缺省值 name: test age: 20 income: 100 instance: //实例列表 - X - Y instaceConfig: X: age: 23 // 具体实例覆盖缺省值字段 Y: name: test4 // 具体实例覆盖缺省值字段
java 代码的预期
Vendor v1 = vendorProvider.create("X"); system.out.print(v1.name) //test system.out.print(v1.age) //23 Vendor v2 = vendorProvider.create("Y"); system.out.print(v2.name) //test4
现在问题是动态的获取 application.yml 中的字段 StringValueResolver 可以满足动态获取但是 但是获取未配置字段时会报出异常 明显并不是优雅的方案 各位有没有人遇上过类似的需求
1 securityCoding 2023-12-18 10:33:40 +08:00 这个是 yaml 库抛出的 runtime 异常吧,你自己包装一个方法就好了? |
![]() | 2 xuanbg 2023-12-18 10:44:05 +08:00 使用变量前自己先判空就行了 |
3 imokkkk 2023-12-18 16:14:46 +08:00 把 getXXX 方法重写了? |
4 fykang 2023-12-19 11:18:36 +08:00 优雅做法你应该写成 map 的方式注入配置,可以参考 security 中关于不同的 resource 的注入 根据你的示例可以改写成 配置文件 ```yml spring: ... vendor: proto: // 原型缺省值 name: test age: 20 income: 100 instance: //实例列表 X: age: 23 // 具体实例覆盖缺省值字段 Y: name: test4 // 具体实例覆盖缺省值字段 ``` 配置类 ```java @Data @ConfigurationProperties(prefix = "vendor") public class VendorProperties { private Instance proto; private Map<String,Instance> instanceMap; @Data public static class Instance{ private Integer age; private String name; private Integer income; } } ``` 注入配置 ```java @Configuration @EnableConfigurationProperties({VendorProperties .class}) public class MayConfigurer { @Autowired private VendorProperties vendorProperties; public void doCreate(){ // todo 拿到这个配置类就可以写的的具体工厂方法了 Instance proto = vendorProperties.getProto(); // 灵活的方式改成遍历 entrySet 的方式最好,下面我就简单写一下获取不同的配置方式 Instance x = vendorProperties.getInstanceMap().get("X"); Instance y = vendorProperties.getInstanceMap().get("Y"); } } ``` |
5 fykang 2023-12-19 11:22:14 +08:00 排版乱了,重新发一下 优雅做法你应该写成 map 的方式注入配置,可以参考 security 中关于不同的 resource 的注入 根据你的示例可以改写成 配置文件 ```yml vendor: proto: # 原型缺省值 age: 20 income: 100 instance: //实例列表 X: age: 23 # 具体实例覆盖缺省值字段 Y: name: test4 # 具体实例覆盖缺省值字段 ``` 配置类 ```java @Data @ConfigurationProperties(prefix = "vendor") public class VendorProperties { private Instance proto; private Map<String,Instance> instanceMap; @Data public static class Instance{ private Integer age; private String name; private Integer income; } } ``` 注入配置 ```java @Configuration @EnableConfigurationProperties({VendorProperties .class}) public class MayConfigurer { @Autowired private VendorProperties vendorProperties; public void doCreate(){ // todo 拿到这个配置类就可以写的的具体工厂方法了 Instance proto = vendorProperties.getProto(); // 灵活的方式改成遍历 entrySet 的方式最好,下面我就简单写一下获取不同的配置方式 Instance x = vendorProperties.getInstanceMap().get("X"); Instance y = vendorProperties.getInstanceMap().get("Y"); } } ``` |
6 fykang 2023-12-19 11:23:11 +08:00 算了,我放弃排版了,你应该能理解吧 |