spring如何引用properties文件里的配置

1.PropertyPlaceholderConfigurer类
它是把属性中的定义的变量(var)替代,spring的配置文件中使用${var}的占位符
< beans >
< bean  id ="configBean"  class ="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
          
< property  name ="location" > < value > db.properties value > property >
bean >  
< bean  id ="dataSource"  class ="org.apache.commons.dbcp.BasicDataSource"  destroy-method ="close" >
    
< property  name ="driverClassName" >< value > ${jdbc.driverClassName} value > property >
    
< property  name ="url" >< value > ${jdbc.url} value > property >
    
< property  name ="username" >< value > ${jdbc.username} value > property >
    
< property  name ="password" >< value > ${jdbc.password} value > property >
bean >
beans >
db.properties文件
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root
2.PropertyOverrideConfigurer类
跟PropertyPlaceholderConfigurer功能一样,不过用法不一样.不用占位符,在属性文件中
直接定义属性的值,这样就允许有默认值
< beans >
< bean  id ="configBean"  class ="org.springframework.beans.factory.config.PropertyOverrideConfigurer" >
           
< property  name ="location" >< value > db.properties value > property >
bean >  
< bean  id ="dataSource"  class ="org.apache.commons.dbcp.BasicDataSource"  destroy-method ="close" >
    
< property  name ="driverClassName" >< value > org.hsqldb.jdbcDriver value > property >
    
< property  name ="url" >< value > jdbc:hsqldb:hsql://production:9002 value > property >
    
< property  name ="username" >< value >test value > property >
    
< property  name ="password" >< value >123456 value > property >
bean >
beans >
db.properties文件
dataSource.username=admin
dataSource.password=9527
在bean实例时,admin,9527将替代test,123456
3其他
1)如果需要引用多个属性,将 configBean 属性改为
< property  name ="locations" >
< list >
< value > db.properties value >
< value > db1.properties value >
list >
property >
2)在ApplactionContext中是自动调用BeanFactoryPostProcessor接口的,如果要在BeanFactory中使用,必须手动添加:
XmlBeanFactory factory  =   new  XmlBeanFactory( new  FileSystemResource( " beans.xml " ));
PropertyPlaceholderConfigurer cfg 
=   new  PropertyPlaceholderConfigurer();
cfg.setLocation(
new  FileSystemResource( " jdbc.properties " ));
cfg.postProcessBeanFactory(factory);
 

你可能感兴趣的:(spring如何引用properties文件里的配置)