1. Spring引入外部配置文件
当Spring配置文件中的Bean属性值过多时,在配置文件中修改或查找某一个Bean的属性非常不方便,这时可以将字面量属性值抽取成一个以properties格式的配置文件来管理这些值。然后在Spring的配置文件中以标签的形式引入这个配置文件为属性赋值,当修改或查找某一属性时,可以直接在properties配置文件中查找即可,不必在众多的标签中逐一查找。
1.1 直接配置属性
springDataSource.xml配置文件
<!-- 配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</bean>
1.2 测试
package com.wyl.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.sql.DataSource;
public class DataSourceTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("springDataSource.xml");
Object source = applicationContext.getBean("dataSource", DataSource.class);
System.out.println(source);
}
}
1.3 控制台输出
org.springframework.jdbc.datasource.DriverManagerDataSource@11053e1
使用直接配置的方式,可以获得数据库连接。
1.4 创建properties配置文件
cfg.preperties外部配置文件
jdbc.url=jdbc:mysql://127.0.0.1:3306/test
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=123
1.5 引入配置文件
在Spring配置文件的xsi:schemaLocation中引入命名空间
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
然后使用context:property-placeholder标签引入外部配置文件,使用${}的方式直接获取配置文件中的属性值
<context:property-placeholder location="classpath:cfg.properties"/>
<!-- 配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
1.6 控制台输出
org.springframework.jdbc.datasource.DriverManagerDataSource@eed359
也可以获取数据源。