2014-02-21 44 views
0

我試圖圍繞Spring如何在未顯式聲明PropertySourcesPlaceholderConfigurer bean時解決屬性佔位符問題。查看通過註釋配置spring到java的現有項目的源代碼。 。 。Spring Java配置和屬性佔位符解決方案

在Spring上下文XML

<context:component-scan base-package="com.myproject.config" /> 

,並在引導了應用程序的其餘部分&配置

package com.myproject.config; 

@Configuration 
@ComponentScan(basePackages = {"com.myproject.app"}) 
@PropertySource("config/${app.env}.properties") 
public class RootConfig { 

} 

這一切都非常漂亮的一個java文件,但我不能爲生命我弄清楚了什麼讓Spring根據環境變量評估$ {...}屬性佔位符語法。我一直無法在春季文檔中找到答案,儘管我知道spring依靠PropertySourcesPlaceholderConfigurer類來做到這一點。什麼時候/如何隱式調用這個類沒有任何線索。它是通過@Configuration註釋,還是在彈簧引導過程的另一部分?

我知道這不是最需要理解的東西,但我不喜歡寫任何東西作爲「春天魔術」。任何洞察這將是驚人的!

回答

0

每彈簧@Configuration documentation,您的RootConfig類必須從某處「引導」,下面是一些示例。

通過AnnotationConfigApplicationContext

AnnotationConfigApplicationContext context = 
     new AnnotationConfigApplicationContext(); 
ccontext.register(RootConfig.class); 

通過的Spring XML

<beans> 
    <context:annotation-config/> 
    <bean class="...RootConfig"/> 
</beans> 

你檢查這是引導RootConfig,看是否有PropertySourcesPlaceholderConfigurer已申報的來源?例如:

<context:property-placeholder/> 
0
@Configuration 
@PropertySource("classpath:property.property") 
public class ConfigClass { 

    @Autowired Environment env; 

    @Bean 
    public Entity getEntity(){ 
     Entity entity = new Entity(); 
     entity.setUsername(env.getProperty("jdbc.username")); 
     entity.setDriverClassName(env.getProperty("jdbc.driverClassName")); 
     entity.setPassword(env.getProperty("jdbc.password")); 
     entity.setUrl(env.getProperty("jdbc.url")); 
     return entity; 
    } 

}