项目中要用到多个微信配置,放到数据库每次去查很麻烦,想到把数据放到配置文件里,用@ConfigurationProperties
注解赋值给数组,并添加根据某个属性获取配置的方法(类似于枚举)
application.yml
test:
configs:
- name: config_1
value: 111
msg: 配置1
- name: config_2
value: 222
msg: 配置2
- name: config_3
value: 333
msg: 配置3
TestProperties
@Component
@ConfigurationProperties(prefix = "test")
public class TestProperties {
@Setter
private List<Config> configs;
@Data
private static class Config {
private String name;
private Integer value;
private String msg;
}
private static TestProperties testProperties;
@Autowired
public void setTestProperties(TestProperties testProperties) {
TestProperties.testProperties = testProperties;
}
/**
* 根据name获取配置
*/
public static Config getByName(String name) {
for (Config c : testProperties.configs) {
if (c.getName().equals(name)) {
return c;
}
}
return null;
}
}
TestController
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/test1")
public Object test1(@RequestParam String name) {
return TestProperties.getByName(name);
}
}