【问题标题】:Spring 3.1 PropertySourcesPlaceholderConfigurer and conditional importSpring 3.1 PropertySourcesPlaceholderConfigurer 和条件导入
【发布时间】:2012-02-09 21:02:19
【问题描述】:

查看 3.1 (http://blog.springsource.org/2011/02/15/spring-3-1-m1-unified-property-management/) 中新的 spring 属性支持,看起来应该可以:

<context:property-placeholder location="/WEB-INF/application-customer-dev.properties,classpath:application-customer.properties" ignore-resource-not-found="true"/>

<import resource="classpath*:com/x/core/security/security-${login.security}.xml"/>

其中 login.security 在 application-customer-dev.properties 中为:

login.security=dev

(并且 security-dev.xml 确实存在于适当的位置)。我错过了一些东西,因为 login.security 无法解决。我希望在 3.1 之前的 spring 版本中出现这种行为,但看起来这应该对 3.1 有效(我们正在使用)?

【问题讨论】:

  • 当你尝试这个时会发生什么?错误,什么都没有,等等?
  • 只是一个错误说明“无法解析占位符'login.security'”。

标签: java spring import


【解决方案1】:

您的链接的脚注 [2]:

[2]:因为&lt;import/&gt; 元素的处理必然发生在调用 BeanFactoryPostProcessors 之前,这意味着即使是 PropertyPlaceholderConfigurer 也无能为力。由于 Environment 及其一组 PropertySource 是在容器刷新之前配置的,因此可以针对 Environment 解析元素中的占位符,而不会出现任何生命周期问题。

更新

根据javadoc for PropertySourcesPlaceholderConfigurerPropertySourcesPlaceholderConfigurerBeanFactoryPostProcessor,所以脚注真正说的是导入已解决安装 PropertySourcesPlaceholderConfigurer,所以它会也不起作用(事实上,在&lt;import/&gt; 被解析时,配置器可能甚至还不存在!)是的,当它安装时它会查看Environment,但你不能使用它在&lt;import/&gt; 内解析,因为当时没有后处理器在运行。其中包括PropertySourcesPlaceholderConfigurer

基本上 Spring XML 上下文设置或多或少是这样的:

  1. 上下文已创建。
  2. Environment 已设置。
  3. 读取 XML(所有 XML,必要时解析导入)。 Bean 定义已创建。
  4. BeanFactoryPostProcessors 已安装并调用,处理 bean 定义。
  5. BeanPostProcessors 已安装。
  6. 根据 bean 定义实例化 Bean。应用了 BeanPostProcessor。

这是一个类似的问题,它导致您不能使用许多后处理器的order 属性在BeanFactoryPostProcessor 之前应用BeanPostProccesor(执行类似使PropertyPlaceholderConfigurer 解析来自@ 的占位符的操作987654336@):该行为是在 Spring 应用程序上下文中硬编码的,因此您必须通过专门化一些 Spring 类来解决它。

【讨论】:

  • 是的,PropertyPlaceholderConfigurer 无法提供帮助(就像默认的 pre-spring 3.1 一样),但是新的 PropertySourcesPlaceholderConfigurer(spring 3.1)将在 Environment 中查找以解析这些值。该脚注基本上确认它应该有效。
  • @KurtPeterschmidt 我已经更新了我的答案,希望现在更清楚了
  • 感谢您的补充说明。
  • 也许只是我的渴望让它以这种方式工作,这模糊了我对博客文章的解释...... :)
【解决方案2】:

我认为您误读了博客@Kurt - 如果在开始创建 bean 定义之前存在包含该属性的属性源,则应该解决它。

因此,解决导入问题的方法有以下两种: 1.使用该参数设置环境变量(-Dlogin.security=dev),默认注册为属性源
2. 以编程方式将文件注册为属性源,在博客文章中提到,通过编写自定义 ApplicationContextInitializer 来注册您的属性源 - 您应该能够使用ResourcePropertySource 来注册基于文件的属性源

【讨论】:

    【解决方案3】:

    @Inject Environment 和使用配置文件应该更容易满足您现在的需求。您不需要替换文件名的一部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-30
      • 2016-07-19
      • 2012-05-10
      • 1970-01-01
      • 2013-03-08
      • 2012-10-16
      • 1970-01-01
      • 2014-06-30
      相关资源
      最近更新 更多