2012-12-06 35 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

問題是使用環境檢索屬性,而不是使用屬性佔位符。 –