java - Spring系统属性解析器定制:

标签 java spring propertyconfigurator

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

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

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

Spring 是否提供了更简单的方法来做到这一点? 感谢您的宝贵时间

最佳答案

简单地说,实现此目的的最简单方法是按照 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
                      });
            }
        });
    }
}

关于java - Spring系统属性解析器定制:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50420048/

相关文章:

java - 奇怪的 Java 问题 : can find one file with short filepath but cannot find another

java - 如何在 @Controller 内的 ModelAndView 消息中添加相对链接

java - Spring 休息模板。如何解析服务器对 POJO 的 XML 响应

java.lang.NoClassDefFoundError : org/apache/log4j/PropertyConfigurator 错误

java - 使用 JPA 和 spring 数据源实例连接到不同的数据源

java - 将纬度和经度( double )数据转换为字节数组,以便将其作为 java 中的 Geometry 或 GeometryCollection 值存储在 mySql 中

java - 如何在 Jackson2 中使用多参数构造函数反序列化枚举?

java - 您应该在哪里配置内容安全策略?

java - 自定义位置中的 Log4j 属性