一、通過 context:property-placeholder 標簽實現配置文件加載
1) 用法:
1、在spring.xml配置文件中添加標簽
<context:property-placeholder ignore-unresolvable="true" location="classpath:redis-key.properties"/>
2、在 spring.xml 中使用 配置文件屬性:$
<!-- 基本屬性 url、user、password --> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /
3、在java文件中使用:
@Value("${jdbc.url}") private String jdbcUrl; // 注意:這里變量不能定義成static
2) 注意點:踩過的坑
在Spring中的xml中使用<context:property-placeholderlocation>標簽導入配置文件時,想要導入多個properties配置文件,如下:
<context:property-placeholderlocation="classpath:db.properties " />
<context:property-placeholderlocation="classpath:zxg.properties " />
結果發現不行,第二個配置文件始終讀取不到,Spring容器是采用反射掃描的發現機制,通過標簽的命名空間實例化實例,當Spring探測到容器中有一個org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的Bean就會停止對剩余PropertyPlaceholderConfigurer的掃描,即只能存在一個實例
如果有多個配置文件可以使用 “,” 分隔
<context:property-placeholderlocation="classpath:db.properties,classpath:monitor.properties" />
可以使用通配符 *
<context:property-placeholderlocation="classpath:*.properties" />
3) 屬性用法
ignore-resource-not-found //如果屬性文件找不到,是否忽略,默認false,即不忽略,找不到文件並不會拋出異常。
ignore-unresolvable //是否忽略解析不到的屬性,如果不忽略,找不到將拋出異常。但它設置為true的主要原因是:
二、通過 util:properties 標簽實現配置文件加載
1) 用法
1、用法示例: 在spring.xml配置文件中添加標簽
<?xml version="1.0" encoding="UTF-8"?>
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 加載配置文件 -->
<util:properties id="jdbc" local-override="true" location="classpath:properties/jdbc.properties"/>
2、在spring.xml 中使用配置文件屬性:#
<!-- dataSource --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="#{jdbc.driverClass}" /> <property name="jdbcUrl" value="#{jdbc.jdbcUrl}" /> <property name="user" value="#{jdbc.user}" /> <property name="password" value="#{jdbc.password}" /> </bean>
3.java文件,讓Spring注入從資源文件中讀取到的屬性的值,,為了簡便,把幾種注入的方式直接寫入到一個文件中進行展示:
@Component public class SysConf { @Value("#{jdbc.url}") private String url;
@Value("#{jdbc}") public void setJdbcConf(Properties jdbc){ url= sys.getProperty("url"); } }
注意:這里的#{jdbc} 是與第1步的id="jdbc" 相對應的
三、通過 @PropertySource 注解實現配置文件加載
使用和 context:property-placeholder 差不多
1、用法示例:在java類文件中使用 PropertySource 注解
@PropertySource(value={"classpath:mail.properties"}) public class ReadProperties { @Value(value="${mail.username}") private String USER_NAME; }