美文网首页
05.基于XML的IOC的案例

05.基于XML的IOC的案例

作者: 吃伏冒有礼貌 | 来源:发表于2020-02-08 23:58 被阅读0次
    • 1.1 案例准备

      新建一个Maven工程,spring02_eesy_02account_xmlioc,在pom.xml中添加一下Dependency,dependecy需要org.springframework,mysql,junit,c3p0,commons-dbutils
    <?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>spring02_eesy_02account_xmlioc</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>jar</packaging>
        <!--为了Idea不用每次都要配置java编译版本-->
        <properties>
            <maven.compiler.source>12</maven.compiler.source>
            <maven.compiler.target>12</maven.compiler.target>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.1.2.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>commons-dbutils</groupId>
                <artifactId>commons-dbutils</artifactId>
                <version>1.4</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.15</version>
            </dependency>
            <dependency>
                <groupId>c3p0</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.1.2</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/junit/junit -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    </project>
    
    准备AccountService,AccountDao,Account实体类,AccountServiceImpl,AccountDaoImpl.
    

    准备Account实体类

    package com.itheima.domain;
    
    import java.io.Serializable;
    
    public class Account  implements Serializable {
        private Integer id;
        private String name;
        private Float 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 Float getMoney() {
            return money;
        }
    
        public void setMoney(Float money) {
            this.money = money;
        }
    
        @Override
        public String toString() {
            return "Account{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", money=" + money +
                    '}';
        }
    }
    
    

    准备 AccountService 接口

    package com.itheima.service;
    
    import com.itheima.domain.Account;
    
    import java.util.List;
    
    public interface IAccountService {
    
        /**
         * 查询所有账户
         * @return
         */
        List<Account> findAllAccount();
    
        /**
         * 通过id查询账户
         * @return
         */
        Account findAccountbyId(Integer accountId);
        /**
         * 保存
         * @param account
         */
        void saveAccount(Account account);
        /**
         * 更新
         * @param account
         */
        void updateAccount(Account account);
        /**
         * 删除
         * @param accountId
         */
        void deleteAccount(Integer accountId);
    
    }
    

    准备 AccountServiceImpl 实现类

    package com.itheima.service.impl;
    
    import com.itheima.dao.IAccountDao;
    import com.itheima.dao.impl.AccountDaoImpl;
    import com.itheima.domain.Account;
    import com.itheima.service.IAccountService;
    import org.springframework.beans.factory.annotation.Autowired;
    
    import java.util.List;
    
    public class AccountServiceImpl implements IAccountService {
        private IAccountDao accountDao;
        public List<Account> findAllAccount() {
            return accountDao.findAllAccount();
        }
    
        public void setAccountDao(IAccountDao accountDao) {
            this.accountDao = accountDao;
        }
    
        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);
        }
    }
    
    

    准备 AccountDao 接口

    package com.itheima.dao;
    
    import com.itheima.domain.Account;
    
    import java.util.List;
    
    /**
     * 账户持久层接口
     */
    public interface IAccountDao {
        /**
         * 查询所有账户
         * @return
         */
        List<Account> findAllAccount();
    
        /**
         * 通过id查询账户
         * @return
         */
        Account findAccountbyId(Integer accountId);
        /**
         * 保存
         * @param account
         */
        void saveAccount(Account account);
        /**
         * 更新
         * @param account
         */
        void updateAccount(Account account);
        /**
         * 删除
         * @param accountId
         */
        void deleteAccount(Integer accountId);
    }
    
    

    准备 AccountDaoImpl 实现类

    package com.itheima.dao.impl;
    
    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.sql.SQLException;
    import java.util.List;
    
    
    public class AccountDaoImpl implements IAccountDao {
        private QueryRunner queryRunner;
    
        public void setQueryRunner(org.apache.commons.dbutils.QueryRunner queryRunner) {
            this.queryRunner = queryRunner;
        }
    
        public List<Account> findAllAccount() {
            try {
                return queryRunner.query("select * from account", new BeanListHandler<Account>(Account.class));
            } catch (SQLException e) {
                throw new RuntimeException();
            }
        }
    
        public Account findAccountbyId(Integer accountId) {
            try {
                return queryRunner.query("select * from account where id = ? ", new BeanHandler<Account>(Account.class),accountId);
            } catch (SQLException e) {
                throw new RuntimeException();
            }
        }
    
        public void saveAccount(Account account) {
            try {
                queryRunner.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
            } catch (SQLException e) {
                throw new RuntimeException();
            }
        }
    
        public void updateAccount(Account account) {
            try {
                queryRunner.update("update  account set name = ?,money = ? where id = ?",account.getId(),account.getName(),account.getMoney());
            } catch (SQLException e) {
                throw new RuntimeException();
            }
        }
    
        public void deleteAccount(Integer accountId) {
            try {
                queryRunner.update("delete from account where id = ? ",accountId);
            } catch (SQLException e) {
                throw new RuntimeException();
            }
        }
    }
    

    在beans.xml中的配置,需要配置service,dao,数据源,QueryRunner.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns="http://www.springframework.org/schema/beans"
           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">
            <property name="accountDao" ref="accountDao"></property>
        </bean>
        <!--配置Dao-->
        <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
            <!--注入QueryRunner-->
            <property name="queryRunner" ref="runner"></property>
        </bean>
        <!--配置QueryRunner-->
       <!--QueryRunner需要配置为多例模式,避免多个dao使用同一个对象时线程互相干扰-->
          <bean id="runner" 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.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property>
            <property name="user" value="root"></property>
            <property name="password" value="password"></property>
        </bean>
    </beans>
    

    接下来在测试类中测试.创建测试类 AccountServiceTest ,进行测试

    package com.itheima.test;
    
    import com.itheima.domain.Account;
    import com.itheima.service.IAccountService;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import java.util.List;
    
    /**
     * 使用Junit单元测试
     */
    public class AccountServiceTest {
        @Test
        public void testFindAll(){
            //获取容器
            ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml") ;
            //获取业务层对象
            IAccountService accountService = (IAccountService) ac.getBean("accountService");
            //执行
            List<Account> accountList = accountService.findAllAccount();
            //打印
            System.out.println(accountList);
        }
        @Test
        public void testFindAccountbyId(){
            //获取容器
            ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml") ;
            //获取业务层对象
            IAccountService accountService = (IAccountService) ac.getBean("accountService");
            //执行
            Account accountbyId = accountService.findAccountbyId(1);
            //打印
            System.out.println(accountbyId);
        }
        @Test
        public void testSaveAccount(){
            //获取容器
            ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml") ;
            //获取业务层对象
            IAccountService accountService = (IAccountService) ac.getBean("accountService");
            Account account = new Account();
            account.setName("xiaohu");
            account.setMoney((float) 900000);
            //执行
            accountService.saveAccount(account);
            //打印
        }
        @Test
        public void testUpdateAccount(){
            //获取容器
            ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml") ;
            //获取业务层对象
            IAccountService accountService = (IAccountService) ac.getBean("accountService");
            //获取Account
            Account account = accountService.findAccountbyId(6);
            account.setMoney((float) 80000);
            account.setName("langx");
            accountService.updateAccount(account);
            //打印
        }
        @Test
        public void testDeleteAccount(){
            ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml") ;
            IAccountService accountService = ac.getBean("accountService",IAccountService.class);
            accountService.deleteAccount(7);
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:05.基于XML的IOC的案例

          本文链接:https://www.haomeiwen.com/subject/hopfpctx.html