手动加载
#properties文件
jdbc.driver=1
<?xml version="1.0" encoding="UTF-8"?>
<!-- 开启context命名空间-->
<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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd
"><!-- 使用context空间加载properties--><context:property-placeholder location="jdbc.properties,jdbc2.properties"/>
<!-- 使用属性占位符${}读取properties文件中的属性--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driver}"/><property name="jdbcUrl" value="2"/><property name="user" value="3"/><property name="password" value="4"/></bean>
</beans>
package org.example;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import javax.sql.DataSource;public class AppForDIAtuoware {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");DataSource dataSource = (DataSource) ctx.getBean("dataSource");System.out.println(dataSource);}
}
技巧
用通配符*可以加载所有properties文件,注意标明路径
同时只能导入本地的文件
<context:property-placeholder location="classpath:*.properties"/>
更通用
<context:property-placeholder location="classpath*:*.properties"/>
总结