2012-12-06 38 views
16

使用它在春季JavaConfig,我可以定义属性源和注入环境定义春天@PropertySource在XML和环境

@PropertySource("classpath:application.properties") 

@Inject private Environment environment; 

我该怎么做,如果在XML? 我正在使用上下文:property-placeholder,并在JavaConfig类@ImportResource中导入xml。但我不能检索的属性定义的属性文件中使用environment.getProperty(“XX”)

<context:property-placeholder location="classpath:application.properties" /> 

回答

5

据我所知,没有纯XML这样的方式。不管怎么说,这里是一些代码,我这样做是上午:

首先,测试:

public class EnvironmentTests { 

    @Test 
    public void addPropertiesToEnvironmentTest() { 

     ApplicationContext context = new ClassPathXmlApplicationContext(
       "testContext.xml"); 

     Environment environment = context.getEnvironment(); 

     String world = environment.getProperty("hello"); 

     assertNotNull(world); 

     assertEquals("world", world); 

     System.out.println("Hello " + world); 

    } 

} 

那么类:

public class PropertySourcesAdderBean implements InitializingBean, 
     ApplicationContextAware { 

    private Properties properties; 

    private ApplicationContext applicationContext; 

    public PropertySourcesAdderBean() { 

    } 

    public void afterPropertiesSet() throws Exception { 

    PropertiesPropertySource propertySource = new PropertiesPropertySource(
      "helloWorldProps", this.properties); 

    ConfigurableEnvironment environment = (ConfigurableEnvironment) this.applicationContext 
      .getEnvironment(); 

    environment.getPropertySources().addFirst(propertySource); 

    } 

    public Properties getProperties() { 
     return properties; 
    } 

    public void setProperties(Properties properties) { 
     this.properties = properties; 
    } 

    public void setApplicationContext(ApplicationContext applicationContext) 
      throws BeansException { 

     this.applicationContext = applicationContext; 

    } 

} 

而且testContext.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<beans ...> 

    <util:properties id="props" location="classpath:props.properties" /> 

    <bean id="propertySources" class="org.mael.stackoverflow.testing.PropertySourcesAdderBean"> 
     <property name="properties" ref="props" /> 
    </bean> 


</beans> 

而props.properties文件:

hello=world 

这很简单,只需使用一个ApplicationContextAware bean并从(Web)ApplicationContext得到ConfigurableEnvironment。然后,只需将PropertiesPropertySource添加到​​

+0

当您指向XML与@ImportResource它不@Configure类工作(“类路径:properties.xml“),但在应用程序中加载它时起作用oncontext就像你的例子。 – surajz

-1

如果您需要的是访问文件“application.properties”的属性“xx”,则可以通过在xml文件中声明以下bean来完成此操作,而无需Java代码:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="location" value="application.properties"/> 
</bean> 

然后,如果你想在一个bean注入属性只是引用它作为一个变量:

<bean id="myBean" class="foo.bar.MyClass"> 
     <property name="myProperty" value="${xx}"/> 
</bean> 
+1

问题是使用环境检索属性,而不是使用属性占位符。 –