Spring使用 Spring的IoC的实现增删该查

Posted 王小码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring使用 Spring的IoC的实现增删该查相关的知识,希望对你有一定的参考价值。

一、环境搭建

1.项目构建,我们在原来的基础上修改即可。

  修改maven工程的pom文件,添加必须的引用:

<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.xhbjava</groupId>
    <artifactId>Spring02</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>Spring02</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.19</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.12</version>
        </dependency>

    </dependencies>
</project>

 

2.数据库建表

create table account(
id int primary key auto_increment,
name varchar(40),
money float
)

3.编写实体类

package com.xhbjava.pojo;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float mmoney;
    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 getMmoney() {
        return mmoney;
    }
    public void setMmoney(Float mmoney) {
        this.mmoney = mmoney;
    }
    
    

}

4.编写持久层代码

package com.xhbjava.dao;

import java.util.List;

import com.xhbjava.pojo.Account;

/**
 * 账户持久层接口
 * 
 * @author mr.wang
 *
 */
public interface IAccoutDao {
    /**
     * 保存账户
     */
    void saveAccount(Account account);
    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);
    /**
     * 删除账户
     * @param accountId
     */
     void deleteAccount(Integer accountId);

    /**
     * 根据id查询账户
     * 
     * @param accountId
     * @return
     */
     Account findById(Integer accountId);
     /**
      * 查询所有账户
      * @return
      */
     List<Account> findAll();

}

 

package com.xhbjava.dao.impl;

import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.xhbjava.dao.IAccountDao;
import com.xhbjava.pojo.Account;

/**
 * 用户持久层接口实现类
 * 
 * @author mr.wang
 *
 */
public class AccountDaoImpl implements IAccountDao {

    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    @Override
    public void saveAccount(Account account) {
        try {
            runner.update("insert into account(name,money)values(?,?)", account.getName(), account.getMmoney());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {
        try {
            runner.update("update account set name=?,money=? where id=?", account.getName(), account.getMmoney(),
                    account.getId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

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

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

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

}

5.编写业务层代码

package com.xhbjava.service;

import java.util.List;

import com.xhbjava.pojo.Account;

/**
 * 账户的业务层接口
 * 
 * @author mr.wang
 *
 */
public interface IAccountService {
    /**
     * 保存账户
     */
    void saveAccount(Account account);
    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);
    /**
     * 删除账户
     * @param accountId
     */
     void deleteAccount(Integer accountId);

    /**
     * 根据id查询账户
     * 
     * @param accountId
     * @return
     */
     Account findById(Integer accountId);
     /**
      * 查询所有账户
      * @return
      */
     List<Account> findAll();


}
package com.xhbjava.service.impl;

import java.util.List;

import com.xhbjava.dao.IAccountDao;
import com.xhbjava.pojo.Account;
import com.xhbjava.service.IAccountService;

/**
 * 账户业务层接口实现类
 * 
 * @author mr.wang
 *
 */
public class AccountServiceImpl implements IAccountService {
    // 此处依赖有待解决
    private IAccountDao accountDao;

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

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

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

    @Override
    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }

    @Override
    public Account findById(Integer accountId) {
        return accountDao.findById(accountId);
    }

    @Override
    public List<Account> findAll() {
        return accountDao.findAll();
    }

}

6.修改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.xhbjava.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    <!-- 配置dao -->
    <bean id="accountDao" class="com.xhbjava.dao.impl.AccountDaoImpl">
        <property name="runner" ref="runner"></property>
    </bean>
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner"
        scope="prototype">
        <constructor-arg name="ds" ref="dataSource" />
    </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/ssm?useSSL=true&amp;serverTimezone=UTC&amp;characterEncoding=UTF-8" />

        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>


</beans>

二、测试

1.编写测试类

package com.xhbjava.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.xhbjava.pojo.Account;
import com.xhbjava.service.IAccountService;

public class testSpring {
    
    @Test
    public void testSaveAccount() {
        //1.使用ApplicationContest接口获取srping容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据beanid获取对象
        IAccountService accountService = (IAccountService) ac.getBean("accountService");
        Account account = new Account();
        account.setName("张三");
        account.setMmoney(3232.90f);
        accountService.saveAccount(account);
        
    }

    @Test
    public void testUpdateAccount() {
        //1.使用ApplicationContest接口获取srping容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据beanid获取对象
        IAccountService accountService = (IAccountService) ac.getBean("accountService");
        Account account = new Account();
        account.setName("张三");
        account.setMmoney(5000f);
        accountService.updateAccount(account);
        
    }

}

2.测试

 

 

 3.发现的问题

  通过上面的测试类可以看出我们的每个测试方法都重新获取了一次 spring 的核心容器,造成了不必要的重复,增加了工作量。可能我们会想到直接在测试类new一个容器类,这样的话需要我们自己写代码来获取容器。能不能测试时直接就编写测试方法,而不需要手动编码来获取容器呢?答案是肯定的。我们在下面的章节中介绍。

以上是关于Spring使用 Spring的IoC的实现增删该查的主要内容,如果未能解决你的问题,请参考以下文章

Spring中的IOC

Ioc容器-BeanPostProcessor-Spring 源码

谈谈spring是如何实现的?

Spring ioc容器

Spring IOC 之 SmartInitializingSingleton

实现IOC功能的简单Spring框架