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

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

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

春天是否提供一种更简便的方法?
谢谢你的时间

最佳答案

简而言之,最简单的方法是遵循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
                      });
            }
        });
    }
}

08-18 14:41
查看更多