在spring的配置文件中,有時我們需要注入很多屬性值,這些屬性全都寫在spring的配置文件中的話,后期管理起來會非常麻煩。所以我們可以把某一類的屬性抽取到一個外部配置文件中,使用時通用spring的EL表達式引入就可以了。這樣可以方便我們管理屬性。
步驟:
1.引入context名稱空間,並使用 <context:property-placeholder location="外部配置文件"/> 引入外部配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <context:component-scan base-package="com.xj"/> <context:property-placeholder location="classpath:jdbc.properties"/> </beans>
2.創建一個外部配置文件jdbc.properties,並設置鍵值對
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/userDb jdbc.userName=root jdbc.password=123456
3.在spring配置文件中通過spEL表達式引入外部配置文件jdbc.properties中的值
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <context:component-scan base-package="com.xj"/> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.userName}"/> <property name="password" value="${jdbc.password}"/> </bean> </beans>