<!--数据库连接池--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///myemployees"/> <property name="username" value="root"/> <property name="password" value="950728"/> </bean>
3.配置JdbcTemplate对象,注入Datasource
<!--配置JdbcTemplate--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <!--JdbcTemplate对象中注入DataSource,源码中是使用setDataSource()方法--> <property name="dataSource" ref="dataSource"></property> </bean>
4.创建一个Service类和Dao类,在Service里面注入Dao,在Dao中注入Jdbc Template对象
在xml配置中开启组件扫描
<?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-context.xsd"> <!--开启组件扫描--> <context:component-scan base-package="com.company"></context:component-scan>
在Service里面注入dao
package com.company.service; import com.company.dao.BookDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class BookService { //在Service里面注入dao @Autowired private BookDao bookDao; }
在dao里面注入jdbc template
package com.company.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository public class BookDaoImpl implements BookDao { //dao里面注入JdbcTemplate @Autowired private JdbcTemplate jdbctemplate; }
package com.company.entity; public class User { private String userId; private String userName; private String userEmail; //get set方法 public String getUserId() { return userId; } public String getUserName() { return userName; } public String getUserEmail() { return userEmail; } public void setUserId(String userId) { this.userId = userId; } public void setUserName(String userName) { this.userName = userName; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } }