天天看點

SSM之Spring系列(四)---- Spring三種方式實作賬戶的 CRUD 操作、Spring 整合 JUnit案例:實作賬戶的 CRUD 操作Spring 整合 JUnit

在上一篇文章我們對 Spring 基于注解的 IoC有了一定的了解,現在我們來看看一個簡單的案例。這個案例将有三種方式實作,分别是XML,半注解,純注解。看完案例之後就了解一下Spring 整合 JUnit。

文章目錄

  • 案例:實作賬戶的 CRUD 操作
    • XML 方式
    • 半注解(XML + 注解)方式
    • 純注解方式
  • Spring 整合 JUnit

案例:實作賬戶的 CRUD 操作

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>org.example</groupId>
    <artifactId>Spring_Day02_anno_ioc</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</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.20</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.10</version>
        </dependency>
    </dependencies>
</project>
           
導入過程有錯的,大家可以去看看我的這兩篇文章。傳送門1 傳送門2
  • 建立資料庫表并編寫對應實體類
create table account(
	id int primary key auto_increment,
	name varchar(40),
	money float
)character set utf8 collate utf8_general_ci;

insert into account(name,money) values('張三',1000);
insert into account(name,money) values('李四',1000);
insert into account(name,money) values('一個Java小白',1000);
           
package com.cz.domain;

import javax.annotation.PreDestroy;
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 +
                '}';
    }
}
           
  • 編寫業務層接口和實作類

業務層接口:

package com.cz.service;

import com.cz.domain.Account;
import java.util.List;

/**
 * 賬戶業務層接口
 */
public interface AccountService {
    /**
     * 查詢所有賬戶
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 根據id查詢賬戶
     * @param accountId
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 儲存
     * @param account
     * @return
     */
    int saveAccount(Account account);

    /**
     * 更新
     * @param account
     * @return
     */
    int updateAccount(Account account);

    /**
     * 删除
     * @param accountId
     * @return
     */
    int removeAccount(Integer accountId);
}
           

實作類:

package com.cz.service.impl;

import com.cz.dao.AccountDao;
import com.cz.domain.Account;
import com.cz.service.AccountService;
import java.util.List;


/**
 * 賬戶的業務層實作類
 */
public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;

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

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

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

    public int saveAccount(Account account) {
        return accountDao.saveAccount(account);
    }

    public int updateAccount(Account account) {
        return accountDao.updateAccount(account);
    }

    public int removeAccount(Integer accountId) {
        return accountDao.removeAccount(accountId);
    }
}

           
  • 編寫持久層接口和實作類

持久層接口:

package com.cz.dao;

import com.cz.domain.Account;
import java.util.List;

/**
 * 賬戶的持久層接口
 */
public interface AccountDao {

    /**
     * 查詢所有賬戶
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 根據id查詢賬戶
     * @param accountId
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 儲存
     * @param account
     * @return
     */
    int saveAccount(Account account);

    /**
     * 更新
     * @param account
     * @return
     */
    int updateAccount(Account account);

    /**
     * 删除
     * @param accountId
     * @return
     */
    int removeAccount(Integer accountId);
}
           

實作類:

package com.cz.dao.impl;

import com.cz.dao.AccountDao;
import com.cz.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 AccountDaoImpl implements AccountDao {

    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 int saveAccount(Account account) {
        try{
            return runner.update("insert into account(name,money)values(?,? )",account.getName(),account.getMoney());
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

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

    public int removeAccount(Integer accountId) {
        try{
            return runner.update("delete from account  where id=?",accountId);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
           
  • 編寫 Spring 配置檔案

    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.cz.service.impl.AccountServiceImpl">
        <!--注入dao-->
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    <!-- 配置dao對象-->
    <bean id="accountDao" class="com.cz.dao.impl.AccountDaoImpl">
        <!--注入QueryRunner-->
        <property name="runner" ref="runner"></property>
    </bean>
    <!-- 配置QueryRunner-->
    <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.cj.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?serverTimezone=UTC&amp;characterEncoding=utf-8"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>
    </bean>
</beans>
           
  • 測試代碼如下:
package com.cz.test;

import com.cz.domain.Account;
import com.cz.service.AccountService;
import org.junit.Assert;
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 ac;
    private AccountService accountService;

    @Before
    public void init(){
        //1.擷取容器
        ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到業務層service對象
        accountService = ac.getBean("accountService",AccountService.class);
    }

    @Test
    public void testFindAll(){
        //執行方法
        List<Account> accounts = accountService.findAllAccount();
        for (Account account : accounts){
            System.out.println(account);
        }
    }

    @Test
    public void testFindOne(){
        //執行方法
        Account account = accountService.findAccountById(1);
        System.out.println(account);
    }

    @Test
    public void testSave(){
        //執行方法
        Account account = new Account();
        account.setName("王五");
        account.setMoney(800000f);
        accountService.saveAccount(account);
        //下面這個方法也是可以的,下面的更新,删除也适用
//        int row = accountService.saveAccount(account);
//        Assert.assertEquals(1,row);
    }

    @Test
    public void testUpDate(){
        //執行方法
        Account account = accountService.findAccountById(3);
        account.setMoney(9000f);
        accountService.updateAccount(account);
    }

    @Test
    public void testDelete(){
        //執行方法
        accountService.removeAccount(4);
    }
}
           
通過上面的測試類,我們把容器的擷取定義到類中去。但仍需要我們自己寫代碼來擷取容器。能不能測試時直接就編寫測試方法,而不需要手動編碼來擷取容器呢?

半注解(XML + 注解)方式

如果想使用注解進行配置,那麼就可以用到上篇文章講解到的注解傳送門。
  • 業務層代碼:
/**
 * 賬戶的業務層實作類
 */
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;
     // 不需要 set 方法...
    // 業務方法跟上面一樣...
           
  • 持久層代碼:
**
 * 賬戶的持久層實作類
 */
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private QueryRunner runner;
    // 不需要 set 方法...
    // 業務方法跟上面一樣...
           
  • 配置檔案
<?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.cz"></context:component-scan>
    <!-- 配置QueryRunner-->
    <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.cj.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?serverTimezone=UTC&amp;characterEncoding=utf-8"/>
        <property name="user" value="root"/>
        <property name="password" value="7107883"/>
    </bean>
</beans>
           
在這個方法中,無法在 QueryRunner 和 ComboPooledDataSource 等第三方類上加注解,是以還是需要配置檔案。

純注解方式

  如果想要使用純注解,那麼我們就需要将配置檔案中還存在的配置也使用注解配置,這時候就需要一些新的注解了。

@Configuration 注解

  • 作用
    • 用于指定目前類是一個

      Spring 配置類

      ,當建立容器時會從該類上加載注解
  • 屬性
    • value

      : 用于指定配置類的位元組碼
  • 注意
    • 擷取容器時需要使用

      AnnotationApplicationContext(有 @Configuration 注解的類.class)

      ,寫了這個之後可以不用寫

      @Configuration

      注解
/**
 * 該類是一個配置類,他的作用和bean.xml是一樣的
 */
@Configuration
public class SpringConfiguration {
  // ...  
}
           
我們已經把配置檔案用類來代替了,但是如何配置建立容器時要掃描的包呢?請看下一個注解。

@ComponentScan 注解

  • 作用
    • 用于指定 Spring 在初始化容器時要掃描的包。
  • 屬性
    • value / basePackages

      :兩者都是用來指定要掃描的包。使用此注解等同于在xml中配置了:

      <context:component-scan base-package="cn.cz"/>

/**
 * 該類是一個配置類,他的作用和bean.xml是一樣的
 */
@Configuration
@ComponentScan(basePackages = "com.cz")
public class SpringConfiguration {
}
           
我們已經配置好了要掃描的包,但是

資料源和 QueryRunner

對象如何從配置檔案中移除呢?請看下一個注解。

@Bean

  • 作用
    • 該注解隻能寫在方法上,表明使用此方法建立一個對象,并且放入 Spring 容器
  • 屬性
    • name

      :用于指定 Bean的

      id

      ,預設值是目前方法的名稱
  • 細節
    • 當我們使用該注解配置方法時,如果方法有參數,那麼 Spring 架構會去容器中查找有沒有可用的 Bean 對象。查找的方式和

      @Autowired

      的作用是一樣
package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;
import java.awt.color.ProfileDataException;
import java.beans.PropertyVetoException;
import java.util.Date;

/**
 * 該類是一個配置類,他的作用和bean.xml是一樣的
 */
@Configuration
@ComponentScan(basePackages = "com.cz")
public class SpringConfiguration {

    /**
     * 用于建立一個QueryRunner對象并且放入 ioc 容器中,多例
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner creatQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 建立一個資料源并且放入 ioc 容器中
     *
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource createDataSource() {
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.cj.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/spring?serverTimezone=UTC&amp;characterEncoding=utf-8");
            ds.setUser("root");
            ds.setPassword("7107883");
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
           
到這裡我們可以删除

bean.xml

了。但是由于沒有了配置檔案,建立資料源的配置又都寫死在類中了。如何把它們配置出來呢?請看下一個注解。

@PropertySource 注解

  • 作用
    • 用于加載

      xxxxx.properties

      檔案中的配置
  • 屬性
    • value[]

      :用于指定配置檔案的名稱和位置
  • 細節
    • 如果配置檔案是在類路徑下,需要寫上

      classpath:

配置檔案

jdbcConfig.properties

:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring?serverTimezone=UTC&characterEncoding=utf-8
jdbc.user=root
jdbc.password=123456
           
package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;

/**
 *Spring 連接配接 資料庫的配置類
 */
@PropertySource("classpath:jdbcConfig.properties")
public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.user}")
    private String user;

    @Value("${jdbc.password}")
    private String password;

    /**
     * 用于建立一個QueryRunner對象并且放入 ioc 容器中,多例
     *
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner creatQueryRunner(DataSource dataSource) {
        return new QueryRunner(dataSource);
    }
    /**
     * 建立一個資料源并且放入 ioc 容器中
     *
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource createDataSource() {
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(user);
            ds.setPassword(password);
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
           
此時我們已經有了兩個配置類,但是他們還沒有關系。如何建立他們的關系呢?請看下一個注解。

@Import

  • 作用
    • 用于導入其他的配置類,被引入的配置類有無

      @Configuration

      注解均可
  • 屬性
    • value[]

      :用于指定其他配置類的位元組碼
/**
 * 該類是一個配置類,他的作用和bean.xml是一樣的
 */
@Configuration
@ComponentScan(basePackages = "com.cz")
@Import(JdbcConfig.class)
public class SpringConfiguration{

}
           
我們已經把要配置的都配置好了,但是新的問題産生了,由于沒有配置檔案了,如何擷取容器呢?

Spring 整合 JUnit

  • 在原本的代碼中,我們需要手動擷取 IoC 容器,并擷取 service 對象
//1.擷取容器
        ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //2.得到業務層service對象
        accountService = ac.getBean("accountService", AccountService.class);
           
  • 但是我們是測試類,應該專注于測試功能,是以需要程式可以幫我們自己建立容器并且注入 service 對象。這時候就需要使用Spring 來整合 JUnit,步驟如下:
  1. 導入依賴
<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
           
當我們使用spring 5.x版本的時候,要求junit的版本必須是4.12及以上
  1. 使用

    @RunWith

    注解替換 JUnit 原本的運作器
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest {
	// ....
}

           
  1. 使用

    @ContextConfiguration

    指定 Spring 配置檔案或者配置類的位置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
}
           

@ContextConfiguration 注解

  • locations 屬性

    :指定 XML 檔案的位置,加上

    classpath:

    關鍵字表示在類路徑下
  • classes 屬性

    :指定注解類所在的位置
  1. 使用

    @Autowired

    注入 service 對象,最終代碼如下
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {

    @Autowired
    private AccountService service;

	// 測試方法...
}