使用spring将属性作为系统属性加载

时间:2015-07-05 04:02:05

标签: spring properties

我正在使用Spring 4.1.6。 我有以下内容:

foo.properties:

 defaultConfig {
    applicationId "com.game"
    minSdkVersion 9
    targetSdkVersion 22
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_5
        targetCompatibility JavaVersion.VERSION_1_5
    }
}

Spring bean:

valueX=a
valueY=b

我有一个非Spring类,它还需要使用来自foo.properties的值。

非春季班:

<context:property-placeholder location="classpath:foo.properties" ignore-unresolvable="false" ignore-resource-not-found="false" />

    <bean id="foo" class="com.foo.bar.MyClass" >
        <property name="someValue" value="${valueX}" />
    </bean>

当Spring加载foo.properties时,有没有办法将所有属性填充到System属性中,这样我就可以使用System.getProperty(“valueY”)获得“valueY”。

我不想在非Spring类中再次加载foo.properties。

1 个答案:

答案 0 :(得分:0)

context:property-placeholder将为您创建一个PropertySourcesPlaceholderConfigurer配置bean。您无法按照here所述的方式以编程方式访问此bean中的属性。

您可以做的是将属性加载到单独的spring bean中,如下所示。

@Bean(name = "mapper")
public PropertiesFactoryBean mapper() {
  PropertiesFactoryBean bean = new PropertiesFactoryBean();
  bean.setLocation(new ClassPathResource("application.properties"));
  return bean;
}

然后使用下面给出的侦听器在完成上下文加载时设置系统属性。得到了这个answer

的代码
@Component
public class YourJobClass implements ApplicationListener<ContextRefreshedEvent> {

    @Resource(name = "mapper")
    private Properties myTranslator;

    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.setProperties(myTranslator);
    }
}
相关问题