Spring系统属性解析器定制:

时间:2018-05-18 22:33:23

标签: java spring propertyconfigurator

我正在开发一个项目,要求我在java spring应用程序中获取环境变量或系统属性,并在将它们注入bean之前对其进行修改。修改步骤是此应用程序工作的关键。

我目前的方法是将变量设置为系统环境变量,然后使用自定义占位符配置器访问上述变量并从bean可以访问的新属性中创建。有a perfect tutorial for this(除了它使用数据库)。

我有一个POC使用这种方法工作正常,但我认为可能有一个更容易的解决方案。也许有一种方法可以将默认占位符配置器扩展为"挂钩"自定义代码,对整个应用程序中的所有属性进行必要的修改。也许有一种方法可以在收集属性之后以及将数据注入bean之前立即运行代码。

春天提供了一种更简单的方法吗? 谢谢你的时间

1 个答案:

答案 0 :(得分:1)

简单地说,实现此目的的最简单方法是按照spring documentation for property management中“操作Web应用程序中的属性源”一节中的说明进行操作。

最后,您通过context-param标记从web.xml引用自定义类:

<context-param>
   <param-name>contextInitializerClasses</param-name>
   <param-value>com.some.something.PropertyResolver</param-value>
</context-param>

这会强制spring在初始化任何bean之前加载此代码。然后你的班级可以这样做:

public class PropertyResolver implements ApplicationContextInitializer<ConfigurableWebApplicationContext>{

    @Override
    public void initialize(ConfigurableWebApplicationContext ctx) {
        Map<String, Object> modifiedValues = new HashMap<>();
        MutablePropertySources propertySources = ctx.getEnvironment().getPropertySources();
        propertySources.forEach(propertySource -> {
            String propertySourceName = propertySource.getName();
            if (propertySource instanceof MapPropertySource) {
                Arrays.stream(((EnumerablePropertySource) propertySource).getPropertyNames())
                      .forEach(propName -> {
                          String propValue = (String) propertySource.getProperty(propName);
                          // do something
                      });
            }
        });
    }
}
相关问题