通過註解實現的實例和通過XML配置實現的實例是同一個實例,只是修改了一部分內容。
通過註解形式配置持久層實現類
@Repository(value = "accountDao")
public class AccountDaoImpl implements AccountDao {
//提供對sql語句操作的API
@Autowired
private QueryRunner queryRunner;
public List<Account> findAllAccount() {
try {
return queryRunner.query("select *from account",new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Account findAccountById(int accountId) {
try {
return queryRunner.query("select *from account where id = ?", new BeanHandler<Account>(Account.class), accountId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void saveAccount(Account account ) {
try {
queryRunner.update("insert into account(name,money) value(?,?)",account.getName(),account.getMoney());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void updateAccount(Account account) {
try {
queryRunner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void deleteAccount(int accountId) {
try {
queryRunner.update("delete from account where id=?",accountId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
通過註解實現業務層實現類
@Service(value = "accountService")
public class AccountServiceImpl implements AccountService {
@Resource(name = "accountDao")
private AccountDao accountDao;
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
public Account findAccountById(int accountId) {
return accountDao.findAccountById(accountId);
}
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
public void deleteAccount(int accountId) {
accountDao.deleteAccount(accountId);
}
}
通過註解形式編寫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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--掃描包-->
<context:component-scan base-package="com.liang"></context:component-scan>
<bean id="queryRunner" 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.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mySpring?serverTimezone=UTC"></property>
<property name="user" value="root"></property>
<property name="password" value="liang"></property>
</bean>
</beans>
以上爲修改部分,修改後也是用XML配置實現的測試代碼進行測試。