一.使用xml配置
参考代码
链接:https://pan.baidu.com/s/1GvDZ3O5_28gZq3iz-isYiw
提取码:ni7r
复制这段内容后打开百度网盘手机App,操作更方便哦
二.使用注解保留bean.xml
使用注解: ------------->参考spring_day02_account_annocation
第一修改 bean.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">
<!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为
context名称空间和约束中-->
<context:component-scan base-package="coom.itheima"></context:component-scan>
<!--Service和Dao都由注解来配置-->
<!--配置Service-->
<!-- <bean id="accountService" class="coom.itheima.service.impl.AccountServiceImpl">-->
<!-- <!–注入dao–>-->
<!-- <property name="accountDao" ref="accountDao"></property>-->
<!-- </bean>-->
<!--配置Dao对象-->
<!-- <bean id="accountDao" class="coom.itheima.dao.impl.AccountDaoImpl">-->
<!-- <!–注入QueryRunner–>-->
<!-- <property name="runner" ref="runner"></property>-->
<!-- </bean>-->
<!--配置QueryRunner-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!--注入数据源-->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!--配置数据源 class="com.mchange.v2.c3p0.ComboPooledDataSource"-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<!--连接数据库的必备信息 jdbc:mysql;//localhost:3306/demo
jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=UTF-8&
zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=UTC
com.mysql.cj.jdbc.Driver
此时本地用的是8.0.18版本的数据库,则依赖包要8.0.18。此时driverClass,jdbc也要做修改
-->
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8&
zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=UTC"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
</beans>
第二步:使用注解来配置
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private QueryRunner runner; //可以交给spring框架 使用Autowired
// public void setRunner(QueryRunner runner) {
// this.runner = runner;
// }
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
//业务层调用持久层
@Autowired
private IAccountDao accountDao; //使用spring框架创建dao对象 使用Autowired注入
// public void setAccountDao(IAccountDao accountDao) {
// this.accountDao = accountDao;
// }