【问题标题】:convert spring xml configuration to java configuration将spring xml配置转换为java配置
【发布时间】:2015-05-30 21:28:40
【问题描述】:

我无法将以下配置转换为 java 配置。

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
      <property name="ignoreResourceNotFound" value="true"/>
      <property name="locations">
        <list>
          <value>classpath*:META-INF/spring/environments/${XXX_env}/*.properties</value>
          <value>file:/etc/XXX/database.properties</value>
        </list>
      </property>
    </bean>

在上面的例子中,XXX_env 是一个环境变量。例如,

export XXX_env=dev

如何将其转换为 Spring Java 配置?这是我的尝试:

@Bean
public PropertyPlaceholderConfigurer propertyConfigurer() throws IOException {
    PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();
    props.setIgnoreResourceNotFound(true);
    props.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
    Resource[] locations;
    PathMatchingResourcePatternResolver classPathResources = new PathMatchingResourcePatternResolver();
    locations = classPathResources.getResources("classpath*:META-INF/spring/environments/"+env()+ "/*.properties");
    props.setLocations(locations);
    Resource location = new FileSystemResource("/etc/XXX/database.properties");
    props.setLocation(location);
    return props;
}

private String env(){
    Map<String, String> env = System.getenv();
    return env.get("XXX_env");
}

@Value("${database.password}")
private String databasePassword;

@Value("${database.url}")
private String databaseUrl;

@Value("${database.username}")
private String databaseUsername;

@Value("${database.driverClassName}")
private String databaseDriverClassName;

【问题讨论】:

  • 为什么不能,是什么问题?
  • 让我更新问题。
  • env() 有问题吗?你也可以使用 Spring 的Environment,它是可注入的。
  • 我认为问题在于从类路径下的目录加载 *.properties 时正则表达式匹配。

标签: java spring spring-mvc properties configuration


【解决方案1】:

建议:

Resource location = new FileSystemResource("/etc/XXX/database.properties");

在位置数组中,然后是 setLocations(locations) 而不是 setLocation(location)

【讨论】:

    猜你喜欢
    • 2011-01-15
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多