带有自定义PropertySource的Spring Boot ConfigurationProperties

问题描述

我有一个弹簧靴,它大量使用@ConfigurationProperties来将我的yaml文件映射到java对象。现在,我将属性外部化并从外部服务中获取它。因此,我创建了一个自定义PropertySource,并将其作为第一个PropertySource添加到MutablePropertySources中。除了用例外,它一切正常,例如,我有一个以firstName作为字段的java对象,然后在Spring Boot尝试获取值key name = first-name时。对于其他PropertySource,它使用所有不同的组合,例如:firstName,first-name等。但是对于我的自定义PropertySource,它仅使用名字。我尝试调试,发现很少有打包的受保护的类用于获取所有可能的组合。我不想重复逻辑以获取给定键的所有可能组合,所以如果我可以做一些事情来形成弹簧,并且如果我做错了并且可以做得更好,请让我知道。

public class CustomPropertySource extends PropertySource<Map<String,Object>> {

public CustomPropertySource(String name,Map<String,Object> source) {
    super(name,source);
}

@Override
public Object getProperty(String s) {
    if(s.startsWith("employee")) {
        System.out.println("in custom employee property");
    }

    Object value = source.get(s);
    System.out.println("key: " + s + " value: " + value);

    return value;
}

}

public class MyPropertyInitializer implements ApplicationContextinitializer<ConfigurableApplicationContext> {

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    val props = new CustomPropertySource("yaml",getProperties());
    final MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
    propertySources.addFirst(props);
}

private Map<String,Object> getProperties() {
    Yaml yaml = new Yaml();
    InputStream inputStream = CCMServiceApplication.class
            .getClassLoader()
            .getResourceAsstream("customer.yml");
    Map<String,Object> obj = yaml.load(inputStream);
    obj.put("employee.first-name","Sachin -O");
    obj.put("employee.last-name","Jain -O");
    obj.put("employee.middle-name","Kumar -O");
    obj.put("employee.first-name","Sachin -O");

    return obj;
}

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...