壹 | 搭建环境与编写代码
- 此篇博客在 基于maven创建Spring入门案例CRUD(基于xml文件) 的基础上进行改进,可先按链接中的博客步骤搭建好项目再使用以下注解步骤。
贰 | 修改bean.xml
- beans中的标签可在spring官方文档中,搜索“xmlns:context”,复制对于的标签内容到项目中即可。
<?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在创建容器时要扫描的包-->
<context:component-scan base-package="com.itheima"/>
<!--配置QueryRunner-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!--注入数据源-->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--连接数据库的必备信息-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///ssm"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
叁 | 修改AccountDaoImpl
@Repository("accountDao") //新增
public class AccountDaoImpl implements IAccountDao {
@Autowired //新增
private QueryRunner runner;
//使用注解将set构造方法删除
// public void setRunner(QueryRunner runner) {
// this.runner = runner;
// }
public List<Account> findAllAccount() {
try{
return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
}catch (Exception e) {
throw new RuntimeException(e);
}
}
肆 | 修改AccountServiceImpl
@Service("accountService") //新增
public class AccountServiceImpl implements IAccountService{
@Autowired //新增
private IAccountDao accountDao;
//使用注解将set构造方法删除
// public void setAccountDao(IAccountDao accountDao) {
// this.accountDao = accountDao;
// }
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
完成。