springIoc案例
一、第一步——配置jar包的坐标
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
二、写包结构
并实现它的增删改查方法
public class AccountDaoImpl implements IAccountDao{
private JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Account> findAllAccount() {
return template.query("select * from account",new BeanPropertyRowMapper<Account>(Account.class));
}
public Account findAccountById(Integer id) {
return template.queryForObject("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),id);
}
public void saveAccount(Account account) {
template.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
}
public void updateAccount(Account account) {
template.update("update account set name = ?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
public void deleteAccount(Integer id) {
template.update("delete from account where id=?",id);
}
}
三、搭建springIoc开发环境——编写xml文件
这种方式需要注意,在类中声明对象时,需要提供set方法。
例:
public class AccountServiceImpl implements IAccountService{
private IAccountDao accountDao;
//因为需要通过set方法注入,所以提供一个set方法
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
}
<?xml version="1.0" encoding="UTF-8"?>