控制第三方资源
§ 数据源对象管理
添加第三方依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
观察源码发现使用的是
set
方法注入
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/spring_db" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
运行代码
DataSource dataSource = (DataSource) ctx.getBean("dataSource") ;
System.out.println(dataSource);
§ 加载properties文件
有
jdbc.properties
文件如下
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db
jdbc.username=root
jdbc.password=root
applicationContext.xml
文件中读取jdbc.properties
中的配置
开启新的空间,新增命名空间
context
,如下方代码第4,7,8行,复制前文,将beans改为context<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-beans.xsd">
使用context空间加载properties文件(加载多个用
,
分割)
- 规范格式
classpath*:*.properties
<context:property-placeholder location="jdbc.properties"/>
bean配置修改占位符
${}
<bean id="dataSource" 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>