Spring系统属性解析器自定义: [英] Spring System Property Resolver Customization:

查看:178
本文介绍了Spring系统属性解析器自定义:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我目前的解决方法是将变量设置为系统环境变量,然后使用自定义占位符配置器访问上述变量,并从中创建bean可以访问的新属性.有为此的完美教程(除了使用数据库).

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

弹簧是否提供了一种更简便的方法? 谢谢您的时间

解决方案

简而言之,最简单的方法是遵循a perfect tutorial for this (except it uses databases).

I have a POC using this approach working fine, but I think there might be an easier solution out there. Perhaps there is an approach to extend the default placeholder configurer to "hook in" custom code to do the necessary modifications for all properties in the entire application. Maybe there is a way to run code immediately after properties are gathered and before data is injected into beans.

Does spring provide an easier way to do this? Thanks for your time

解决方案

Simply put, the easiest way to accomplish this is to follow the directions under the section "Manipulating property sources in a web application" in the spring documentation for property management.

In the end, you reference a custom class from a web.xml through a context-param tag:

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

This forces spring to load this code before any beans are initialized. Then your class can do something like this:

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
                      });
            }
        });
    }
}

这篇关于Spring系统属性解析器自定义:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆