XML自动装配及外部属性文件的引入
一、 xml自动装配
1. 自动装配
- 根据指定装配规则(属性名称或者属性类型),Spring自动将匹配的属性值进行注入
- 日常使用少,基本使用注解方式
2. 演示过程
- 实现自动装配
- bean标签属性autowire,配置自动装配
- autowire属性常用两个值:
- byName:根据属性名注入,注入值bean的id值和类属性名一样
- byType:根据属性类型注入
<bean id="emp" class="" autowire="byName"></bean>
<bean id="dept" class=""></bean>
二、 外部属性文件引入
1. 直接配置数据库信息 (druid)
-
引入德鲁伊连接池依赖jar包
-
配置连接池
<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/userDb"/> <property name="username" value="root" /> <property naem="password" value="root" /> </bean>
2. 引入外部属性文件配置数据库连接
-
创建外部属性文件,properties格式文件,写数据库信息
# jdbc.properties prop.driverClass=com.mysql.jdbc.Driver prop.url=jdbc:mysql://localhost:3306/userDb prop.userName=root prop.password=root
-
把外部properties属性文件引入到xml配置中
-
引入context名称空间
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">
-
引入外部属性文件
<context:property-placeholder location="classpath:jdbc.properties" />
-
配置连接池
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${prop.driverClass}" /> <property name="url" value="${prop.url}"/> <property name="username" value="${prop.username}" /> <property naem="password" value="${prop.password}" /> </bean>
-