Spring5 – 学习笔记 - 3.IoC容器
1、用到的相关jar包
链接:https://pan.baidu.com/s/1u_2F541EWXZPqQJII8aCfQ
提取码:vq25
2、配置外部属性文件用到的场景
一般用到的场景为配置数据库连接池,比如数据库的用户、密码、url等写到一个外部的配置文件(properties)中。
用到的连接池为,德鲁伊连接池。
3、直接方式进行配置连接池
导入德鲁伊连接池jar包。
找到德鲁伊的jar包。
在xml文件中配置连接池。
<!--直接配置连接池-->
<bean id="dataSource1" class="com.alibaba.druid.pool.DruidDataSource" autowire="byName">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
3、引用外部属性文件配置连接池
创建外部属性文件,.properties格式文件,并写入相关数据库参数。
把properties属性文件引入到spring配置文件中。
首先引入名称空间,context。
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
">
在spring中使用一个标签,引入外部属性文件。
<!--引入配置文件
location的值为配置文件的路径及名称
-->
<context:property-placeholder location="classpath:jdbc.properties " />
外部属性文件方式配置连接池。
<!--外部文件配置连接池
将原先的value值变为表达式 ${key} key为properties配置文件中的键值
-->
<bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource" autowire="byName">
<property name="driverClassName" value="${prop.driverClass}"></property>
<property name="url" value="${prop.url}"></property>
<property name="username" value="${prop.userName}"></property>
<property name="password" value="${prop.password}"></property>
</bean>