注:本文不做技术交流贴,仅仅是学习笔记性质,如有繆误,敬请指正。
参考B站spring尚硅谷王泽老师的课
第一步创建
1. 创建Service类 给service整体添加@service注解
2. 创建Dao接口及接口实现类DaoImpl给DaoImpl添加@Repository注释
第二步注入
1.在Service里面添加 private Dao dao 创建dao;
@Autowired或者@Qualifier或者@inject
private Dao dao;
2.在DaoImpl里面注入相应的属性(赋值)
同上
@Autowired
private JdbcTemplate jdbcTemplate;注这个是老师的例子,
这一步需要给jdbcTemplate注入相应的属性:
1.src子目录下创建xml文件(如下所示)
开启注解扫描
配置druid数据库连接池
配置jdbcTemplate和data source属性
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 组件扫描 -->
<context:component-scan base-package="com.project"></context:component-scan>
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="jdbc:mysql:///user_db" />
<property name="username" value="root" />
<property name="password" value="root" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
</bean>
<!-- JdbcTemplate对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--注入dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>