搜索 K
Appearance
博客正在加载中...
Appearance
我们使用注解改造上一篇博客中的案例
我们可以先清空 bean.xml 文件的内容。由于我们使用的注解,那么 XML 的名称空间和约束是不一样的,并且需要加上扫描的包的配置,此外 service 和 dao 的 bean 我们都可以不要了:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<context:component-scan base-package="com.peterjxl"/>
<!-- 配置数据源 -->
<bean id = "dataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
<property name = "jdbcUrl" value = "jdbc:mysql://localhost:3306/learnSpring"/>
<property name = "user" value = "learnSpringUser"/>
<property name = "password" value = "learnSpringPassword"/>
</bean>
<!-- 配置QueryRunner -->
<bean id = "runner" class = "org.apache.commons.dbutils.QueryRunner" scope = "prototype">
<constructor-arg name = "ds" ref = "dataSource"/>
</bean>
</beans>我们在 dao 中添加注解,并且可以去掉 set 方法:
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao; service 层同理,加上注解并去掉 set 方法:
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;此时我们可以测试下 AccountServiceTest 中的方法,可以看到是能正常运行的
本项目已将源码上传到 GitHub 和 Gitee 上。并且创建了分支 demo6,读者可以通过切换分支来查看本文的示例代码。