【Spring之配置propertie資原始檔】Maven整合spring profiles功能配置propertie資原始檔更靈活、簡單
spring 框架的xml檔案如何讀取properties檔案資料
第一步:在spring配置檔案中
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>/db.properties</value> </list> </property> </bean>
第二步:
user=sa
password=sa
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;databaseName=DB1
第三步:
${user}
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>/db.properties</value> </list> </property> </bean> <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${driver}"> </property> <property name="url" value="${url}"> </property> <property name="username" value="${user}"></property> <property name="password" value="${password}"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="datasource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> </props> </property> <property name="mappingResources"> <list> <value>entity/Users.hbm.xml</value> </list> </property> </bean> <bean id="UsersDAO" class="dao.UsersDAO"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> </beans>
spring為beans標籤提供了profile功能,以便專案的開發和生成環境分離。
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
< 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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
< beans
profile = "dev,test" >
< context:property-placeholder
location = "classpath:application.properties"
/>
< bean
id = "dataSource"
class = "com.jolbox.bonecp.BoneCPDataSource"
destroy-method = "close" >
< property
name = "driverClass"
value = "${db.driver}" />
< property
|