目录
案例:数据源对象管理
①在maven中导入坐标
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.11</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.16</version> </dependency>
②配置数据源对象作为spring管理的bean
<!-- Druid--> <bean id="DruidDataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/brand"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <!--c3p0--> <bean id="C3P0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/brand"/> <property name="user" value="root"/> <property name="password" value="123456"/> </bean>
总结:如何配置第三方资源,首先查看提供的资源如何进行构造的是用setter还是构造器,选择进行配置,具体的属性功能是干什么的可以查看文档,最重要的就是触类旁通,会一个其他的都就会了。
加载properties文件
properties文件
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/brand jdbc.user=root jdbc.password=123456
1.开启context命名空间
<?xml version="1.0" encoding="UTF-8"?> <!--新增xmlns:context,以及在xsi:schemaLocation新增两个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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">
2.使用context空间加载properties文件
<context:property-placeholder location="jdbc.properties"/> <!-- 加载多个配置文件--> <context:property-placeholder location="jdbc.properties,jdbc2.properties"/> <!-- 加载所有配置文件--> <context:property-placeholder location="*.properties"/> <!-- 最严谨的形式,以后都用这个--> <context:property-placeholder location="classpath:*.properties"/> <!-- 上面的都只能从当前工程中读取--> <!-- 下面classpath加个*,不仅可以从当前工程中读,还可以从所依赖的jar包中读取--> <context:property-placeholder location="classpath*::*.properties"/>
3.使用属性占位符${}读取properties文件中的属性
<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.user}"/> <property name="password" value="${jdbc.password}"/> </bean>
细节:
配置文件中的变量名如果与系统环境变量冲突,那么优先使用的是系统环境变量。
解决方法: 在context命名空间加system-properties-mode属性为NEVER
<context:property-placeholder location="jdbc.properties" system-properties-mode="NEVER"/>