java - 同时使用 PropertyPlaceholderConfigurer 和 PropertySource

标签 java spring spring-annotations

我在这里遇到了一些困难。我正在设计一个实用程序,我需要 Spring 上下文能够将命令行参数视为属性。这很容易完成:

if (args != null && args.length > 0) {
    PropertySource<?> ps = new SimpleCommandLinePropertySource(args);
    ctx.getEnvironment().getPropertySources().addFirst(ps);
}

我遇到的问题是下一步:为了符合我的企业框架,我必须设置他们提供的 PropertyPlaceholderConfigurer1。也很容易完成。

@Bean
public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
    return new MyPropertyPlaceholderConfigurer();
}

问题是,一旦设置了后者,之前在命令行中使用的内容就不再适用,并且我遇到了错误:

java.lang.IllegalArgumentException: Could not resolve placeholder 'input.file' in string value "${input.file}"

现在,我知道使用两者都远非理想(理想情况下,我什至不应该使用 PropertyPlaceholderConfigurer 而是使用 PropertySourcesPlaceholderConfigurer)。然而,我对配置程序别无选择。

因此,我认为我必须对我的 PropertySource 进行一些更改,但我不知道如何以优雅的方式做到这一点。我应该扩展 PropertyPlaceholderConfigurer 来添加 PropertySource 吗?这可能吗?

在这种情况下最好的解决方案是什么?即使是模糊的线索也是受欢迎的,因为我不知道该走哪条路。

( Spring 版本:4.1.6)

<小时/>

<子>1。此 PropertyPlaceholderConfigurer 加载一些属性文件并应用一些额外的处理(例如,允许属性文件中的加密值)。

最佳答案

随着

 ctx.getEnvironment().getPropertySources().addFirst(ps);

你走对了路。

我认为您的 MyPropertyPlaceholderConfigurer(来自该企业框架)不仅与 PropertySourcesPlaceholderConfigurer 兼容。

您应该查看他们的代码并覆盖它以扩展 PropertySourcesPlaceholderConfigurer

从另一边来看,PlaceholderConfigurerSupport是一个BeanFactoryPostProcessor,这些家伙必须配置为静态@Bean

HTH

关于java - 同时使用 PropertyPlaceholderConfigurer 和 PropertySource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33547837/

相关文章:

java - 使用 PowerMock 避免 wait() 方法时出现 IllegalMonitorStateException

java - 将当前日期时间(实时)与上次修改的文件进行比较

java - 为什么 Java 编译器拒绝将 System.exit() 识别为过程终止?

java - 扩展 HttpEntityEnshingRequestBase 时出错

spring - Spring中@Bean注解和@Component注解有什么区别?

java - 一个应用程序中有多个 Spring @Transactional 注释?

java - 如何禁用 AspectJ 转储文件 "ajcore.txt"

java - 在 JSP 中 Autowiring Spring Beans 的最干净的方法是什么?

spring - 如何在 Spring DM 中获得 BundleContext?

java - Tomcat 7 的 Spring 配置类处理器错误