Spring第六篇_基于XML的IOC案例

15 篇文章 0 订阅

1. 案例前的准备

1.1 创建 day02_eesy_02account_xmlioc 工程
1.2 完成 pom.xml 的配置, 导入坐标(各种依赖)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itheima</groupId>
    <artifactId>day02_eesy_02account_xmlioc</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.7</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
    </dependencies>

</project>
1.3 创建实体类

实体类 Account.java的各项属性与数据库表 account的各列 相对应

public class Account {

    private Integer id;

    private String name;

    private Double money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

1.4 创建持久层接口 IAccountDao.java
//账户的持久层接口
public interface IAccountDao {

    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     */
    Account findAccountById(Integer accountId);

    /**
     * 保存
     */
    void saveAccount(Account account);

    /**
     * 更新
     */
    void updateAccount(Account account);


    void deleteAccount(Integer accountId);
}

1.5 创建持久层实现类AccountDaoImpl.java
import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.List;

/**
 * 账户的持久层实现类
 */
public class AccountImpl implements IAccountDao {

    private QueryRunner runner;

    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);
        }
    }

    public Account findAccountById(Integer accountId) {
        try {
            return runner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),accountId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void saveAccount(Account account) {

        try {
           runner.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public void updateAccount(Account account) {

        try {
            runner.update("update account set name=?, money=? where id=? ",account.getName(),account.getMoney(),account.getId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public void deleteAccount(Integer accountId) {

        try {
            runner.update("delete from  account where id=? ",accountId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

说明: 本例中用 dbutils 框架完成对数据库的操作

1.6 创建业务层接口 IAccountService.java
/**
 * 账户的业务层接口
 */
public interface IAccountService {

    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     */
    Account findAccountById(Integer accountId);

    /**
     * 保存
     */
    void saveAccount(Account account);

    /**
     * 更新
     */
    void updateAccount(Account account);


    void deleteAccount(Integer accountId);
}
1.7 创建业务层实现类 AccountServiceImpl.java
import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;

import java.util.List;
//账户的业务层实现类
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }
}
1.8 目录结构

2. 编写Spring的IOC配置

创建bean.xml配置文件,在bean.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">


    <!--配置Service-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <!--注入dao-->
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置dao对象-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountImpl">
        <!--注入QueryRunner-->
        <property name="runner" ref="runner"></property>
    </bean>

    <!--配置QueryRunner-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"> <!--QueryRunner的默认作用范围是单例的,为了避免线程之间的相互影响,将其设置为多例的-->
        <!--注入数据源-->
        <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://localhost:3306/eesy"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

</beans>

3. 测试基于XML的IOC案例

创建测试类AccountServiceTest.java,完成测试
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * 使用Junit单元,测试我们的配置
 */
public class AccountServiceTest {

    private ApplicationContext applicationContext;

    private IAccountService accountService;

    @Before
    public void init(){
//        1. 获取容器
        applicationContext=new ClassPathXmlApplicationContext("bean.xml");
//        2. 得到业务层对象
        accountService=applicationContext.getBean("accountService",IAccountService.class);


    }


    @Test
    public void testFindAll(){
//        3. 执行方法
        List<Account> accounts = accountService.findAllAccount();

        for(Account account:accounts){
            System.out.println(account);
        }

    }

    @Test
    public void testFindById(){

//        3. 执行方法
        Account account=accountService.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave(){
//        3. 执行方法
        Account account = new Account();
        account.setName("test");
        account.setMoney(12345.0);
        accountService.saveAccount(account);

    }

    @Test
    public void testUpdate(){
//        3. 执行方法
        Account account = accountService.findAccountById(4);
        account.setMoney(1234.0);
        accountService.updateAccount(account);
    }

    @Test
    public void testDelete(){

        accountService.deleteAccount(4);
    }
}

目录结构:

4. 使用注解配置实现该案例

1. 创建 day02_eesy_03account_annoioc 工程
2. 在项目配置文件 pom.xml中完成配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itheima</groupId>
    <artifactId>day02_eesy_03account_annoioc</artifactId>
    <version>1.0-SNAPSHOT</version>


    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.7</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
    </dependencies>
</project>
3. 将day02_eesy_02account_xmlioc工程src/main目录下的文件复制到day02_eesy_03account_annoioc工程的src/main目录下
4. 将day02_eesy_02account_xmlioc工程src/test目录下的文件复制到day02_eesy_03account_annoioc工程的src/test目录下
5. 修改配置文件 bean.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
        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"></context:component-scan>

    <!--配置QueryRunner-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"> <!--QueryRunner的默认作用范围是单例的,为了避免线程之间的相互影响,将其设置为多例的-->
        <!--注入数据源-->
        <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://localhost:3306/eesy"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

</beans>
4. 对业务层实现类AccountServiceImpl.java添加注解
//账户的业务层实现类
@Service("accountService")
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }
}
5. 对持久层实现类 AccountDaoImpl.java添加注解
/**
 * 账户的持久层实现类
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private QueryRunner runner;

    public List<Account> findAllAccount() {
        try {
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Account findAccountById(Integer accountId) {
        try {
            return runner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),accountId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void saveAccount(Account account) {

        try {
           runner.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public void updateAccount(Account account) {

        try {
            runner.update("update account set name=?, money=? where id=? ",account.getName(),account.getMoney(),account.getId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public void deleteAccount(Integer accountId) {

        try {
            runner.update("delete from  account where id=? ",accountId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

6. 在测试类AccountServiceTest.java中测试
/**
 * 使用Junit单元,测试我们的配置
 */
public class AccountServiceTest {

    private ApplicationContext applicationContext;

    private IAccountService accountService;

    @Before
    public void init(){
//        1. 获取容器
        applicationContext=new ClassPathXmlApplicationContext("bean.xml");
//        2. 得到业务层对象
        accountService=applicationContext.getBean("accountService",IAccountService.class);


    }


    @Test
    public void testFindAll(){
//        3. 执行方法
        List<Account> accounts = accountService.findAllAccount();

        for(Account account:accounts){
            System.out.println(account);
        }

    }

    @Test
    public void testFindById(){

//        3. 执行方法
        Account account=accountService.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave(){
//        3. 执行方法
        Account account = new Account();
        account.setName("test");
        account.setMoney(12345.0);
        accountService.saveAccount(account);

    }

    @Test
    public void testUpdate(){
//        3. 执行方法
        Account account = accountService.findAccountById(4);
        account.setMoney(1234.0);
        accountService.updateAccount(account);
    }

    @Test
    public void testDelete(){

        accountService.deleteAccount(4);
    }
}
7. 目录结构

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值