目錄
基於xml的IoC案例
一、準備
1. 新建一個maven工程:
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.veeja</groupId>
<artifactId>spring_day02_02</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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</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>
3. 建立數據庫,準備數據
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('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);
4. 創建賬戶實體類
package com.veeja.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 +
'}';
}
}
5. 業務層
① 接口IAccountService
package com.veeja.service;
import com.veeja.domain.Account;
import java.util.List;
/**
* 賬戶的業務層接口
*
* @author veeja
*/
public interface IAccountService {
/**
* 查詢所有用戶的信息
*
* @return
*/
List<Account> findAllAccount();
/**
* 根據id查詢一個用戶
*
* @param accountId
* @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.veeja.service.impl;
import com.veeja.dao.IAccountDao;
import com.veeja.domain.Account;
import com.veeja.service.IAccountService;
import java.util.List;
/**
* 賬戶的業務層實現類
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public List<Account> findAllAccount() {
return accountDao.findAll();
}
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@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);
}
}
6. 持久層
① 接口IAccountDao
package com.veeja.dao;
import com.veeja.domain.Account;
import java.util.List;
/**
* 用戶的持久層接口
*
* @author veeja
*/
public interface IAccountDao {
/**
* 查詢所有用戶
*
* @return
*/
List<Account> findAll();
/**
* 通過id查詢用戶
*
* @param accountId
* @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.veeja.dao.impl;
import com.veeja.dao.IAccountDao;
import com.veeja.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 runner;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
@Override
public List<Account> findAll() {
try {
return runner.query("select * from account", new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public Account findAccountById(Integer accountId) {
try {
return runner.query("select * from account where id = ?",
new BeanHandler<Account>(Account.class), accountId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void saveAccount(Account account) {
try {
runner.update("insert into account(name,money) values(?,?)",
account.getName(), account.getMoney());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void updateAccount(Account account) {
try {
runner.update("update account set name=?,money=? where id = ?",
account.getName(), account.getMoney(), account.getId());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteAccount(Integer accountId) {
try {
runner.update("delete account where id = ?", accountId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
二、編寫Spring的IoC配置
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.veeja.service.impl.AccountServiceImpl">
<!--注入dao對象-->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置dao對象-->
<bean id="accountDao" class="com.veeja.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.jdbc.Driver"></property>
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/mybatisdatabase?useUnicode=true&characterEncoding=utf8">
</property>
<property name="user" value="root"></property>
<property name="password" value="0000"></property>
</bean>
</beans>
三、測試類的測試方法
package com.veeja.test;
import com.veeja.domain.Account;
import com.veeja.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() {
// 1.獲取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 2.得到業務層對象
IAccountService accountService = ac.getBean("accountService", IAccountService.class);
// 3.執行方法
List<Account> accounts = accountService.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
@Test
public void testFindOne() {
// 1.獲取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 2.得到業務層對象
IAccountService accountService = ac.getBean("accountService", IAccountService.class);
// 3.執行方法
Account account = accountService.findAccountById(1);
System.out.println(account);
}
@Test
public void testSave() {
// 1.獲取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 2.得到業務層對象
IAccountService accountService = ac.getBean("accountService", IAccountService.class);
Account account = new Account();
account.setMoney(500f);
account.setName("veeja");
// 3.執行方法
accountService.saveAccount(account);
}
@Test
public void testUpdate() {
// 1.獲取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 2.得到業務層對象
IAccountService accountService = ac.getBean("accountService", IAccountService.class);
// 3.執行方法
Account account = accountService.findAccountById(4);
account.setMoney(500000f);
accountService.updateAccount(account);
}
@Test
public void testDelete() {
// 1.獲取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 2.得到業務層對象
IAccountService accountService = ac.getBean("accountService", IAccountService.class);
// 3.執行方法
accountService.deleteAccount(4);
}
}
四、基於註解的改造
接下來纔是我們的重頭戲,我們要對上面的demo進行改造,使用註解的方式來完成上面的功能。
1. 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.veeja"></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>
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/springdatabase?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC"/>
<property name="user" value="root"></property>
<property name="password" value="0000"></property>
</bean>
</beans>
2. 業務層實現類
package com.veeja.service.impl;
import com.veeja.dao.IAccountDao;
import com.veeja.domain.Account;
import com.veeja.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 賬戶的業務層實現類
*
* @author veeja
*/
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public List<Account> findAllAccount() {
System.out.println("AccountServiceImpl.findAllAccount()...");
return accountDao.findAll();
}
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@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);
}
}
3. 持久層實現類
package com.veeja.dao.impl;
import com.veeja.dao.IAccountDao;
import com.veeja.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.sql.SQLException;
import java.util.List;
/**
* 賬戶的持久層實現類
*
* @author veeja
*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private QueryRunner runner;
@Override
public List<Account> findAll() {
System.out.println("AccountDaoImpl.findAll()...");
try {
return runner.query("select * from account", new BeanListHandler<Account>(Account.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Account findAccountById(Integer accountId) {
try {
return runner.query("select * from account where id = ?",
new BeanHandler<Account>(Account.class), accountId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void saveAccount(Account account) {
try {
runner.update("insert into account(name,money) values(?,?)",
account.getName(), account.getMoney());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void updateAccount(Account account) {
try {
runner.update("update account set name=?,money=? where id = ?",
account.getName(), account.getMoney(), account.getId());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteAccount(Integer accountId) {
try {
runner.update("delete from account where id = ?", accountId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
五、Spring的純註解配置
我們現在發現一個問題,那就是雖然我們進行了註解的改造,可是還是有bean.xml文件,文件裏面還是有一堆配置,我們有沒有辦法把這些東西也給拿掉呢???
當然,我們也需要注意一下,我們選擇哪種配置的原則是簡化開發和配置方便,而非追求某種技術。
1. 問題
我們發現,之所以我們離不開XML配置文件,是因爲我們有一句很關鍵的配置。
<!--告知spring容器在創建容器的時候要掃描的包-->
<context:component-scan base-package="com.veeja"></context:component-scan>
另外,數據源和JdbcTemplate的配置也需要靠註解來實現。
<!--配置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>
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/springdatabase?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC"/>
<property name="user" value="root"></property>
<property name="password" value="0000"></property>
</bean>
如果我能能把這兩個配置都通過註解實現。這樣就能使用純註解的方式。
2. @Configuration
用於指定當前類是一個 spring 配置類,當創建容器時會從該類上加載註解。獲取容器時需要使用 AnnotationApplicationContext(有@Configuration 註解的類.class)。
屬性:
value
:用於指定配置類的字節碼
例如,我們新建一個類,並加上註解:
package config;
import org.springframework.context.annotation.Configuration;
/**
* 這個類是一個配置類,它的作用和bean.xml是一樣的
*/
@Configuration
public class SpringConfiguration {
}
我們已經把配置文件用類來代替了,但是如何配置創建容器時要掃描的包呢?
3. @ComponentScan
用於指定 spring 在初始化容器時要掃描的包。
作用和在 spring 的 xml 配置文件中的: <context:component-scan base-package="com.itheima"/>
是一樣的。
屬性:
basePackages
:用於指定要掃描的包。和該註解中的 value 屬性作用一樣。
例如:
/**
* 這個類是一個配置類,它的作用和bean.xml是一樣的
*/
@Configuration
@ComponentScan("com.veeja")
public class SpringConfiguration {
}
我們已經配置好了要掃描的包,接下來的問題就是數據源和 JdbcTemplate 對象如何從配置文件中移除。
4. @Bean
該註解只能寫在方法上,表明使用此方法創建一個對象,並且放入 spring 容器。
屬性:
name
:給當前@Bean 註解方法創建的對象指定一個名稱(即 bean 的 id)。
例如:
/**
* 這個類是一個配置類,它的作用和bean.xml是一樣的
*/
@Configuration
@ComponentScan(basePackages = "com.veeja")
public class SpringConfiguration {
/**
* 用於創建一個QueryRunner對象
*
* @param dataSource
* @return
*/
@Bean(name = "runner")
public QueryRunner createQueryRunner(DataSource dataSource) {
return new QueryRunner(dataSource);
}
/**
* 創建數據源對象
*
* @return
*/
@Bean(name = "dataSource")
public DataSource createDataSource() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/springdatabase?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC");
dataSource.setUser("root");
dataSource.setPassword("0000");
} catch (PropertyVetoException e) {
e.printStackTrace();
}
return dataSource;
}
}
當我們使用註解配置方法時,如果方法有參數,spring框架會去容器中查找有沒有可用的bean對象。
查找的方式和Autowired註解的作用是一樣的
5. AnnotationConfigApplicationContext
這個時候我們可以把bean給刪掉了,因爲我們已經把xml中所有的配置都轉移到我們的配置類中去了。
可是我們打開測試類,忽然發現一個新的問題:
小朋友你是否有很多的問號,我們是把bean.xml刪除了啊,可是我們在測試類中還在讀取它呢?
不過沒關係,我們也有我們的解決方案:
那就是使用我們超級長長長的AnnotationConfigApplicationContext類
。
例如:
@Test
public void testFindAll() {
// 1.獲取容器
// ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
// 2.得到業務層對象
IAccountService accountService = ac.getBean("accountService", IAccountService.class);
// 3.執行方法
List<Account> accounts = accountService.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
這樣也是可以運行的。
6. @Configuration
的省略
我們如果把配置類上的註解@Configuration去掉,我們發現,程序還是可以運行的,那是因爲我們在創建AnnotationConfigApplicationContext對象的時候,把配置類作爲參數了,這個時候,註解是可以不寫的。
如果我們這個時候新建另一個配置類:JdbcConfig
我們把之前的配置都轉移到這個裏面來了:
/**
* 和spring連接數據庫相關的配置類
*/
public class JdbcConfig {
/**
* 用於創建一個QueryRunner對象
*
* @param dataSource
* @return
*/
@Bean(name = "runner")
@Scope("prototype")
public QueryRunner createQueryRunner(DataSource dataSource) {
return new QueryRunner(dataSource);
}
/**
* 創建數據源對象
*
* @return
*/
@Bean(name = "dataSource")
public DataSource createDataSource() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/springdatabase?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC");
dataSource.setUser("root");
dataSource.setPassword("0000");
} catch (PropertyVetoException e) {
e.printStackTrace();
}
return dataSource;
}
}
這個時候我們再運行測試方法,肯定是不行的了。
-
可是我們可以這麼改造,首先在SpringConfiguration的掃描的包裏面,加上config這個包。
/** * 這個類是一個配置類,它的作用和bean.xml是一樣的 */ @Configuration @ComponentScan(basePackages = {"com.veeja", "config"}) public class SpringConfiguration { }
這個時候,JdbcConfig類上的註解@Configuration就沒法再省略了!必須加上!
/** * 和spring連接數據庫相關的配置類 */ @Configuration public class JdbcConfig { ...... }
-
當然我們也可以這麼改造:我們兩個地方的註解都省略掉,但是我們在創建AnnotationConfigApplicationContext對象的時候,就要把這兩個類都寫上:
// 1.獲取容器 // ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class, JdbcConfig.class);
這樣也是沒有問題的。
7. @Import
可是這個時候我們發現,AnnotationConfigApplicationContext對象的創建變得有些臃腫,或者是SpringConfiguration上需要添加要掃描的包,這看上去都不是很好。
這個時候我們就可以使用@Import
註解了:
作用:
用於導入其他配置類,在引入其他配置類時,可以不用再寫@Configuration 註解。當然,寫上也沒問 題。
屬性:
value[]
:用於指定其他配置類的字節碼。
例如上面的一些操作我們都可以這樣的修改:
SpringConfiguration: 省略了@SpringConfiguration,添加@Import註解
/**
* 這個類是一個配置類,它的作用和bean.xml是一樣的
*/
@ComponentScan(basePackages = {"com.veeja", "config"})
@Import(JdbcConfig.class)
public class SpringConfiguration {
}
JdbcConfig: 省略了@SpringConfiguration
/**
* 和spring連接數據庫相關的配置類
*/
public class JdbcConfig {
...
...
}
測試類中, 也不需要寫JdbcConfig.class:
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
也是可以成功的。
8. @PropertySource
這裏還是有個問題,我們辛苦這麼半天,正如我們以前說的,我們做這些都是爲了解耦。
可是,jdbc的配置的四項好像又寫死了:
我們該怎麼做呢?
我們在resources文件夾下建立一個jdbcConfig.properties
:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springdatabase
jdbc.username=root
jdbc.password=0000
我們先介紹一下@PropertySource
註解:
作用:
用於加載.properties 文件中的配置。例如我們配置數據源時,可以把連接數據庫的信息寫到 properties 配置文件中,就可以使用此註解指定 properties 配置文件的位置。
屬性:
value[]:用於指定 properties 文件位置。如果是在類路徑下,需要寫上 classpath:
。
接下來我們開始改造JdbcConfig:
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.*;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
/**
* 和spring連接數據庫相關的配置類
*/
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 用於創建一個QueryRunner對象
*
* @param dataSource
* @return
*/
@Bean(name = "runner")
@Scope("prototype")
public QueryRunner createQueryRunner(DataSource dataSource) {
return new QueryRunner(dataSource);
}
/**
* 創建數據源對象
*
* @return
*/
@Bean(name = "dataSource")
public DataSource createDataSource() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
System.out.println("driver:" + driver);
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
return dataSource;
}
}
然後我們在SpringConfiguration上使用新的註解:
/**
* 這個類是一個配置類,它的作用和bean.xml是一樣的
*/
@ComponentScan(basePackages = {"com.veeja", "config"})
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
}
這樣也是沒有問題的。
六、Spring整合JUnit
1. 問題
我們的測試類中,每個測試方法都會有下面兩行代碼:
這兩行代碼的作用是獲取容器,如果不寫的話,直接會提示空指針異常。所以又不能輕易刪掉。
2. 思路
針對上述問題,我們需要的是程序能自動幫我們創建容器。一旦程序能自動爲我們創建 spring 容器,我們就 無須手動創建了,問題也就解決了。
我們都知道,junit 單元測試的原理(在 web 階段課程中講過),但顯然,junit 是無法實現的,因爲它自 己都無法知曉我們是否使用了 spring 框架,更不用說幫我們創建 spring 容器了。不過好在,junit 給我們暴露 了一個註解,可以讓我們替換掉它的運行器。
這時,我們需要依靠 spring 框架,因爲它提供了一個運行器,可以讀取配置文件(或註解)來創建容器。我 們只需要告訴它配置文件在哪就行了。
3. 操作過程
注意!!!
當我們使用Spring 5.x版本的時候,要求JUnit的版本必須是4.12及以上。
① 導入jar包
我們要添加一個新的jar包,spring-test,座標如下:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
② 使用@RunWith
註解替換原有運行器
在我們的測試類上添加:
/**
* 使用Junit單元測試,測試我們的配置
*/
@RunWith(SpringJUnit4ClassRunner.class)
public class AccountServiceTest {
...
}
③ 使用@ContextConfiguration 指定 spring 配置文件的位置
我們要告知Spring的運行器,Spring和IoC的創建是基於xml還是註解的,並且說明位置。
@ContextConfiguration
註解:
locations
屬性:用於指定配置文件的位置。如果是類路徑下,需要用 classpath:表明
classes
屬性:用於指定註解的類。當不使用 xml 配置時,需要用此屬性指定註解類的位置。
例如:
/**
* 使用Junit單元測試,測試我們的配置
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private IAccountService accountService = null;
@Test
public void testFindAll() {
List<Account> accounts = accountService.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
}
這樣就可以了。