spring 资源属性配置文件5种加载方式

一.spring获取资源属性值${key名称}与#{key名称}区别
1)用户获取外部文件中指定key的值;
2)可以出现在xml配置文件中,也可以出现在注解@Value中;
3)一般用户获取数据库配置文件的内容信息;

#{key名称}:
1)SpEL表达式的格式:  SpEL:Spring Expression Language,spring的一套表达式,主要应用在IOC容器进行对象属性的注入。格式为:#{表达式}
  在使用的时候也允许#{‘${key}’}这样使用。2)可以出现在xml配置文件中,也可以出现在注解@Value中
3)可以任意表达式,支持运算符。

二.资源文件获取方式
 
【前提条件:】 
1.工程resources目录结果如下: 
-----resources 
-----resources/label/label.properties 
-----resources/conf_dev/report-jdbc.properties 
-----resources/conf_dev/business-jdbc.properties 
-----resources/conf_test/report-jdbc.properties 
-----resources/conf_test/business-jdbc.properties 
-----resources/conf_pre/report-jdbc.properties 
-----resources/conf_pre/business-jdbc.properties 
-----resources/conf_prod/report-jdbc.properties 
-----resources/conf_prod/business-jdbc.properties 
-----resources/spring 
-----resources/spring/spring.xml 
-----resources/spring/spring-dao.xml 

2.文件label.properties内容如下: 
system.label=dev 

3.公共系统环境配置  
 

【加载配置方法一:】 
 
 
注意:多个资源属性文件,使用逗号分隔(,)

【加载配置方法二:】  
 

 
 
   
  classpath:conf_#{label['system.label']}/*jdbc.properties



 
注意:PropertyPlaceholderConfigurer类Bean的id 与标签的id是等同的,

【加载配置方法三:】
id="conf" ocation="classpath:conf_#{label['system.label']}/*jdbc.properties"  />注意:多个资源属性文件,使用逗号分隔(,)
【加载配置方法四:】
在java代码中,使用 @PropertySource 注解实现配置文件加载:
import org.springframework.beans.factory.annotation.Value;
@Service
@PropertySource(value={"classpath:conf_#{label['system.label']}/*jdbc.properties"}
public class ComboPooledDataSource {
 @Value("#{conf['dataSource.master.driverClassName']}")
 private String driverClass;
} 

【加载配置方法五:】
使用PropertiesFactoryBean方式

    //本地资源 读取方式,用流读取资源进行加载。
        
            classpath:conf_#{label['system.label']}/*jdbc.properties
        
    


三.案例:
根据该id获取资源属性值语法:#{id名['资源属性名']}, 比如:#{conf['dataSource.master.driverClassName']} 
1)xml文件中获取资源属性值: 

 
 ......
 

2)java类中注解获取资源属性值: 
import org.springframework.beans.factory.annotation.Value; 
@Service 
public class ComboPooledDataSource { 
 @Value("#{conf['dataSource.master.driverClassName']}") 
 private String driverClass; 
} 

注意:
1)@Value方式支持Service、DAO、JavaBean类;但类成员属性不能为final、static。
2)如在引入资源文件中,不设置id="conf"时,在使用时不需要使用conf,例如:@Value("#{dataSource.master.driverClassName}")3)资源文件加载配置需放值spring.xml文件最顶端,否则部分代码导不入属性值。

 

你可能感兴趣的:(spring 资源属性配置文件5种加载方式)