spring使用外部属性文件
在进行数据源或者邮件服务器等资源的配置时,可以直接在spring配置文件中用户名,密码,连接地址等配置信息,但是更好的一种做法是将这些配置信息独立到一个外部属性文件中。
优点:
1,减少维护的工作量。资源的配置信息可以被多个应用共享,如果需要发生改变,只需要调整这个独立的外部资源文件。
2,使部署更简单。在软件部署时,应用部署人员只需要修改这个独立的外部属性资源文件即可。
?
?(一)直接将配置信息写在xml配置文件中
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="dataSource" destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/testdb" p:userName="root" p:password="1234"/></beans>
?(二)对上面的配置进行优化
?首先我们将配置信息抽到一个资源文件中(例如:jdbc.properties)。
driverClassName=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/testdbuserName=rootpassword=1234
?(三)替换原配置文件中的配置信息。替换后如下图所示
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="dataSource" destroy-method="close" p:driverClassName="${driverClassName}" p:url="${url}" p:userName="${userName}" p:password="${password}"/></beans>?(四)替换以后,最关键的地方是,我们如何将properties的配置和xml关联起来呢?
我们要在xml配置中引入外部属性文件。
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- 引入外部属性文件 --> <bean destroy-method="close" p:driverClassName="${driverClassName}" p:url="${url}" p:userName="${userName}" p:password="${password}"/></beans>?(五)使用context命名空间替代PropertyPlaceholderConfigurer,这样更优雅。
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <!-- 引入外部属性文件 --> <context:property-placeholder location="classpath:spring3/pripertyFile/jdbc.properties" file-encoding="utf8"/> <bean id="utf8" destroy-method="close" p:driverClassName="${driverClassName}" p:url="${url}" p:userName="${userName}" p:password="${password}"/></beans>?
?