Spring入門筆記--spring載入properties檔案
阿新 • • 發佈:2022-05-15
spring載入properties檔案
以JDBC為例
<?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-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <bean id="databaseTest" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/mall?serverTimezone=UTC"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> </beans>
之前通過bean依賴注入--普通資料型別,注入了jdbc連線引數,現在將這些屬性放到一個獨立的properties檔案中:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mall?serverTimezone=UTC
jdbc.username=root
jdbc.password=root
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: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"> <!--載入外部properties檔案,先引入context名稱空間,第4,7,8行所示--> <!--載入外部properties檔案--> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="databaseTest" 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>