2016-02-05 240 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+

,只是使用过的位置需要