2016-02-05 294 views
0

我已經讀了幾十篇關於Spring的文章,但找不到這個問題的優雅解決方案。彈簧屬性配置

a)使用PropertyPlaceholderConfigurer加載屬性文件。例如。

// Load properties file 
@Bean(name = "appProperties") 
public static PropertyPlaceholderConfigurer getApplicationProperties() { 
PropertyPlaceholderConfigurer bean = new PropertyPlaceholderConfigurer(); 
bean.setLocation(new ClassPathResource("app.properties")); 
return bean; 
} 

b)求使用PropertyPlaceHolderConfigurer(例如mysql.properties在與此相關的數據庫類型 「app.properties」 app.database = MySQL的

C),然後負載屬性中配置的數據庫類型)並使其在上下文豆類

可用
+0

嗨@Romail ${property name},請看看這個:http://kruders.com/spring/spring-propertyplaceholderconfigurer-使用註釋/ – Backtrack

+0

此鏈接不起作用。我想根據app.properties中定義的屬性加載新的屬性文件 –

回答

0
@Bean 
    public static PropertyPlaceholderConfigurer properties(){ 
     PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); 
     ClassPathResource[] resources = new ClassPathResource[ ] 
     { new ClassPathResource("db.properties") }; 
     ppc.setLocations(resources); 
     ppc.setIgnoreUnresolvablePlaceholders(true); 
     return ppc; 
    } 

    @Value("${jdbc.url}") private String jdbcUrl; 
    @Value("${jdbc.driverClassName}") private String driverClassName; 
    @Value("${jdbc.username}") private String username; 
    @Value("${jdbc.password}") private String password; 

    @Bean(name="datasource") 
    public DataSource datasource() { 
     BasicDataSource ds = new BasicDataSource(); 
     ds.setDriverClassName(driverClassName); 
     ds.setUrl(jdbcUrl); 
     ds.setUsername(username); 
     ds.setPassword(password); 
     return ds; 
    } 

我覺得上面可能會有幫助

創建db.properties,其中包含您的數據庫詳細信息

jdbc.driverClassName=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql://localhost:3306/test 
jdbc.username=root 
jdbc.password= 
+0

這沒有幫助。我希望根據app.properties中定義的屬性動態更改位置「db.properties」。因此對於例如如果在app.properties中我有「app.database = mysql」,那麼我想加載「mysql.properties」。如果我有「app.database = h2」,那麼我想加載「h2.properties」 –

-1

試試這個。

@ComponentScan(basePackageClasses = "name of package where you are writing the class") 
@PropertySource({ "classpath:(properties file name).properties"}) 

@Configuration 
public class RootAppConfig { 


    @Bean 
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 
    return new PropertySourcesPlaceholderConfigurer(); 
    } 
} 

這是用彈簧4.0+

,只是使用過的位置需要