项目结构
在此,直接引用上一篇基于XML配置文件的IoC案例的代码进行修改,避免一些重复的操作。节约一些篇幅,部分方法也删除了,仅保留查询所有用于测试。
一、在持久层添加Repository注解
就是在类的头部加上@Repository(“accountDao”),accountDao是该类的标识,用于创建该类的对象。
/**
* 账户的持久层实现类
*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private QueryRunner queryRunner;
@Override
public List<Account> findAll() {
try {
return queryRunner.query("select * from account",new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
二、在业务层添加Service注解
/**
* 账户的业务层实现类
*/
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public List<Account> findAll() {
return accountDao.findAll();
}
}
三、测试
结果是一样的
四、一些问题
- 注解IoC仍然还有XMl
- 测试类中存在很多重复的代码