Spring系统属性解析器定制:

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

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

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

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

简而言之,实现此目的的最简单方法是按照弹出文档中“属性管理中操作Web应用程序中的属性源”一节中的说明进行操作 。

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

  contextInitializerClasses com.some.something.PropertyResolver  

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

 public class PropertyResolver implements ApplicationContextInitializer{ @Override public void initialize(ConfigurableWebApplicationContext ctx) { Map 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 }); } }); } }