Spring的新注解

Spring的新注解

1 注解Configuration和ComponentScan
1.打开IDEA工具如图所示的界面,点击Create New Project。在这里插入图片描述
2.选择Maven工程和JDK的版本,如图所示:并点击Next。在这里插入图片描述
3.填写项目名称和保存的地址,点击Finish。如图所示:在这里插入图片描述
4.导入相应的依赖jar包的代码如下:

<?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.txw</groupId>
    <artifactId>spring_04account_annoioc_withoutxml</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--打包的方式 -->
    <packaging>jar</packaging>
    <dependencies>
        <!--导入spring-context的依赖jar包坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <!--导入lombok的依赖jar包坐标-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <!--导入mysql的依赖jar包坐标-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <!--导入commons-dbutils的依赖jar包坐标-->
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.7</version>
        </dependency>
        <!--导入spring-test的依赖jar包坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <!--导入c3p0的依赖jar包坐标-->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <!--导入junit的依赖jar包坐标-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
    </dependencies>
</project>

5.编写账户实体类的代码如下:

package com.txw.domain;

import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
 * 账户的实体类
 * @author:Adair
 * @QQ:1578533828
 */
@Data     // 自动生成set和get方法
@ToString // 重写toString方法
@SuppressWarnings("all")      // 注解警告信息
public class Account implements Serializable {
    private Integer id;      // 账户的id
    private String name;     // 账户的名称
    private Float money;     // 账户的金额
}

6.编写账户的业务层接口代码如下:

package com.txw.service;

import com.txw.domain.Account;
import java.util.List;
/**
 *账户的业务层接口
 * @author:Adair
 * @QQ:1578533828
 */
@SuppressWarnings("all")      // 注解警告信息
public interface AccountService {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();
    /**
     * 根据id查询一个
     * @return
     */
    Account findAccountById(Integer accountId);
    /**
     * 保存账户
     * @param account
     */
    void saveAccount(Account account);
    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);
    /**
     * 根据id删除
     * @param acccountId
     */
    void deleteAccount(Integer accountId);
}

7.编写账户的业务层实现类代码如下:

package com.txw.service.impl;

import com.txw.dao.AccountDao;
import com.txw.domain.Account;
import com.txw.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * 账户的业务层实现类
 * @author:Adair
 * @QQ:1578533828
 */
@Service("accountService")
@SuppressWarnings("all")      // 注解警告信息
public class AccountServiceImpl implements AccountService {
    // 声明AccountDao业务对象
    @Autowired
    private AccountDao accountDao;
    /**
     * 查询所有
     * @return
     */
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }
    /**
     * 根据id查询一个
     * @return
     */
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }
    /**
     * 保存账户
     * @param account
     */
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }
    /**
     * 修改账户
     * @param account
     */
    public void updateAccount(Account account) {
    accountDao.updateAccount(account);
    }
    /**
     * 根据id删除
     * @param acccountId
     */
    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }
}

8.编写账户的持久层接口代码如下:

package com.txw.dao;

import com.txw.domain.Account;
import java.util.List;
/**
 * 账户的持久层接口
 * @author:Adair
 * @QQ:1578533828
 */
@SuppressWarnings("all")      // 注解警告信息
public interface AccountDao {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();
    /**
     * 根据id查询一个
     * @return
     */
    Account findAccountById(Integer accountId);
    /**
     * 保存账户
     * @param account
     */
    void saveAccount(Account account);
    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);
    /**
     * 根据id删除
     * @param acccountId
     */
    void deleteAccount(Integer accountId);
}

9.编写账户的持久层实现类代码如下:

package com.txw.dao.impl;

import com.txw.dao.AccountDao;
import com.txw.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.util.List;
/**
 * 账户的持久层实现类
 * @author:Adair
 * @QQ:1578533828
 */
@Repository("accountDao")
@SuppressWarnings("all")      // 注解警告信息
public class AccountDaoImpl implements AccountDao {
    // 声明QueryRunner业务对象
    @Autowired
    private QueryRunner runner;
    /**
     * 查询所有
     * @return
     */
    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 根据id查询一个
     * @return
     */
    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);
        }
    }
    /**
     * 保存账户
     * @param account
     */
    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);
        }
    }
    /**
     * 修改账户
     * @param account
     */
    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);
        }
    }
    /**
     * 根据id删除
     * @param accountId
     */
    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id=?",accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

11.编写配置类的代码如下:

package com.txw.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 * spring中的新注解
 * Configuration
 *     作用:指定当前类是一个配置类
 *     细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。
 * ComponentScan
 *      作用:用于通过注解指定spring在创建容器时要扫描的包
 *      属性:
 *          value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
 *                 我们使用此注解就等同于在xml中配置了:
 *                      <context:component-scan base-package="com.txw"></context:component-scan>
 */
@Configuration
@ComponentScan("com.txw")
@SuppressWarnings("all")      // 注解警告信息
public class SpringConfiguration {
}

这时说明bean.xml里如图所示的代码,就可以删除!在这里插入图片描述
2 spring的注解Bean
如图所示:在这里插入图片描述
这时此在配置类编写相关的代码,即可。代码如下:

package com.txw.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;

/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 * spring中的新注解
 * Configuration
 *     作用:指定当前类是一个配置类
 *     细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。
 * ComponentScan
 *      作用:用于通过注解指定spring在创建容器时要扫描的包
 *      属性:
 *          value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
 *                 我们使用此注解就等同于在xml中配置了:
 *                      <context:component-scan base-package="com.txw"></context:component-scan>
 *  Bean
 *      作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
 *      属性:
 *          name:用于指定bean的id。当不写时,默认值是当前方法的名称
 *      细节:
 *          当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象。
 *          查找的方式和Autowired注解的作用是一样的
 */
@Configuration
@ComponentScan("com.txw")
@Import(JdbcConfig.class)
@SuppressWarnings("all")      // 注解警告信息
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(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false");
            ds.setUser("root");
            ds.setPassword("123456");
            return ds;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

这时resources目录下bean.xml剩余的内容如图所示:也可直接删除!在这里插入图片描述
编写测试的代码如下:

package com.txw.test;

import com.txw.config.SpringConfiguration;
import com.txw.domain.Account;
import com.txw.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
/**
 * 使用Junit单元测试:测试我们的配置
 * @author:Adair
 * @QQ:1578533828
 */
@SuppressWarnings("all")      // 注解警告信息
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
    // 声明AccountService业务对象
    @Autowired
    private AccountService as;
    /**
     * 测试查询所有
     */
    @Test
    public void testFindAll() {
        // 1.执行方法
        List<Account> accounts = as.findAllAccount();
        for(Account account : accounts){
            System.out.println(account);
        }
    }
    /**
     * 测试根据id查询一个
     */
    @Test
    public void testFindOne() {
        // 1.执行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }
    /**
     * 测试保存账户
     */
    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("Adair");
        account.setMoney(12345f);
        // 1.执行方法
        as.saveAccount(account);
    }
    /**
     * 测试修改账户
     */
    @Test
    public void testUpdate() {
        // 1.执行方法
        Account account = as.findAccountById(5);
        account.setMoney(23456f);
        as.updateAccount(account);
    }
    /**
     * 测试根据id删除
     */
    @Test
    public void testDelete() {
        // 1.执行方法
        as.deleteAccount(4);
    }
}

运行结果如图所示:在这里插入图片描述
3 AnnotationConfigApplicationContext的使用
编写测试的代码如下:

package com.txw.test;

import com.txw.config.SpringConfiguration;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
 * 测试queryrunner是否单例
 */
public class QueryRunnerTest {
    @Test
    public  void  testQueryRunner(){
        // 1.获取容易
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        // 2.获取queryRunner对象
        QueryRunner runner = ac.getBean("runner",QueryRunner.class);
        QueryRunner runner1 = ac.getBean("runner",QueryRunner.class);
        System.out.println(runner == runner1);
    }
}

运行结果如图所示:说明是单例的!在这里插入图片描述
在配置类配置如图所示的代码:在这里插入图片描述
再次运行结果如图所示:说明是多例的!在这里插入图片描述
4 spring的注解Import
如图所示:把@Configuration注释。在这里插入图片描述
再次运行测试查询所有的方法,会出现如图所示的结果!并不影响。在这里插入图片描述
1.编写配置类的代码如下:

package com.txw.config;

import org.springframework.context.annotation.*;
/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 * spring中的新注解
 * Configuration
 *     作用:指定当前类是一个配置类
 *     细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。
 * ComponentScan
 *      作用:用于通过注解指定spring在创建容器时要扫描的包
 *      属性:
 *          value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
 *                 我们使用此注解就等同于在xml中配置了:
 *                      <context:component-scan base-package="com.txw"></context:component-scan>
 *  Bean
 *      作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
 *      属性:
 *          name:用于指定bean的id。当不写时,默认值是当前方法的名称
 *      细节:
 *          当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象。
 *          查找的方式和Autowired注解的作用是一样的
 *  Import
 *      作用:用于导入其他的配置类
 *      属性:
 *          value:用于指定其他配置类的字节码。
 *                  当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类
 */
//@Configuration
@ComponentScan("com.txw")
@SuppressWarnings("all")      // 注解警告信息
public class SpringConfiguration {
}

2.编写和spring连接数据库相关的配置类的代码如下:

package com.txw.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;
/**
 * 和spring连接数据库相关的配置类
 */
@SuppressWarnings("all")      // 注解警告信息
public class JdbcConfig {
    /**
     * 用于创建一个QueryRunner对象
     * @param dataSource
     * @return
     */
    @Bean(name="runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner( DataSource dataSource){
        return new QueryRunner(dataSource);
    }
    @Bean(name="dataSource")
    public DataSource createDataSource1(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false");
            ds.setUser("root");
            ds.setPassword("123456");
            return ds;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

3.再次运行测试查询所有的方法,会出现如图所示的错误!在这里插入图片描述
4.解决的办法是在和spring连接数据库相关的配置类如图所示的代码:在这里插入图片描述
5.再次运行测试查询所有的方法,会出现如图所示的结果!在这里插入图片描述
6.在配置类加上如图所示的Import注解:在这里插入图片描述
7.在和spring连接数据库相关的配置类如图所示:在这里插入图片描述
8.再次运行测试查询所有的方法,会出现如图所示的结果!在这里插入图片描述
5 spring的注解PropertySource
1.如图所示,说明又写死。在这里插入图片描述
2.这时,就可以在resources目录下创建jdbcConfig.properties的代码如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false
jdbc.username=root
jdbc.password=123456

3.编写和spring连接数据库相关的配置类的代码如下:

package com.txw.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;
/**
 * 和spring连接数据库相关的配置类
 */
@SuppressWarnings("all")      // 注解警告信息
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(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

4.编写配置类的代码如下:

package com.txw.config;

import org.springframework.context.annotation.*;
/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 * spring中的新注解
 * Configuration
 *     作用:指定当前类是一个配置类
 *     细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。
 * ComponentScan
 *      作用:用于通过注解指定spring在创建容器时要扫描的包
 *      属性:
 *          value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
 *                 我们使用此注解就等同于在xml中配置了:
 *                      <context:component-scan base-package="com.txw"></context:component-scan>
 *  Bean
 *      作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
 *      属性:
 *          name:用于指定bean的id。当不写时,默认值是当前方法的名称
 *      细节:
 *          当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象。
 *          查找的方式和Autowired注解的作用是一样的
 *  Import
 *      作用:用于导入其他的配置类
 *      属性:
 *          value:用于指定其他配置类的字节码。
 *                  当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类
 *  PropertySource
 *      作用:用于指定properties文件的位置
 *      属性:
 *          value:指定文件的名称和路径。
 *                  关键字:classpath,表示类路径下
 */
//@Configuration
@ComponentScan("com.txw")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
@SuppressWarnings("all")      // 注解警告信息
public class SpringConfiguration {
}

5.编写测试的代码如下:

package com.txw.test;

import com.txw.config.SpringConfiguration;
import com.txw.domain.Account;
import com.txw.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
/**
 * 使用Junit单元测试:测试我们的配置
 * @author:Adair
 * @QQ:1578533828
 */
@SuppressWarnings("all")      // 注解警告信息
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
    // 声明AccountService业务对象
    @Autowired
    private AccountService as;
    /**
     * 测试查询所有
     */
    @Test
    public void testFindAll() {
        // 3.执行方法
        List<Account> accounts = as.findAllAccount();
        for(Account account : accounts){
            System.out.println(account);
        }
    }
    /**
     * 测试根据id查询一个
     */
    @Test
    public void testFindOne() {
        //3.执行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }
    /**
     * 测试保存账户
     */
    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("Adair");
        account.setMoney(12345f);
        //3.执行方法
        as.saveAccount(account);

    }
    /**
     * 测试修改账户
     */
    @Test
    public void testUpdate() {
        //3.执行方法
        Account account = as.findAccountById(5);
        account.setMoney(23456f);
        as.updateAccount(account);
    }
    /**
     * 测试根据id删除
     */
    @Test
    public void testDelete() {
        //3.执行方法
        as.deleteAccount(4);
    }
}

运行查询所有的结果如图所示:在这里插入图片描述
6 Qualifier注解的另一种用法
1.编写和spring连接数据库相关的配置类的代码如下:有多个数据源。

package com.txw.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;
/**
 * 和spring连接数据库相关的配置类
 */
@SuppressWarnings("all")      // 注解警告信息
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="ds2")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name="ds1")
    public DataSource createDataSource1(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false");
            ds.setUser("root");
            ds.setPassword("123456");
            return ds;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

2.运行会报如下的错误!

java.lang.IllegalStateException: Failed to load ApplicationContext
	at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
	at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123)
	at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
	at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
	at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
	at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
	at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
	at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
	at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
	at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountDao': Unsatisfied dependency expressed through field 'runner'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'runner' defined in com.txw.config.JdbcConfig: Unsatisfied dependency expressed through method 'createQueryRunner' parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected single matching bean but found 2: ds2,ds1
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)
	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130)
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1420)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516)
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551)
	at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
	at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
	at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:275)
	at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:243)
	at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
	at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
	... 25 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'runner' defined in com.txw.config.JdbcConfig: Unsatisfied dependency expressed through method 'createQueryRunner' parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected single matching bean but found 2: ds2,ds1

如图所示:在这里插入图片描述
解决办法,如图所示:使用@Qualifier。在这里插入图片描述
4.运行结果如图所示,就不会报错!在这里插入图片描述
7 spring整合junit问题分析
在测试类中,每个测试方法都有以下两行代码:
ApplicationContext ac = new ClassPathXmlApplicationContext(“bean.xml”);
IAccountService as = ac.getBean(“accountService”,IAccountService.class);
这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。
针对上述问题,我们需要的是程序能自动帮我们创建容器。一旦程序能自动为我们创建spring容器,我们就无须手动创建了,问题也就解决了。
我们都知道,junit 单元测试的原理(在 web 阶段课程中讲过),但显然,junit 是无法实现的,因为它自己都无法知晓我们是否使用了 spring 框架,更不用说帮我们创建 spring 容器了。不过好在,junit 给我们暴露了一个注解,可以让我们替换掉它的运行器。
这时,我们需要依靠 spring 框架,因为它提供了一个运行器,可以读取配置文件(或注解)来创建容器。我们只需要告诉它配置文件在哪就行了。
使用@ContextConfiguration 指定 spring 配置文件的位置的命令如下:

@ContextConfiguration 注解: 
 locations 属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明 
 classes 属性:用于指定注解的类。当不使用 xml 配置时,需要用此属性指定注解类的位置。

使用@Autowired 给测试类中的变量注入数据。如图所示:在这里插入图片描述
测试的代码如下:

package com.txw.test;

import com.txw.config.SpringConfiguration;
import com.txw.domain.Account;
import com.txw.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
/**
 * 使用Junit单元测试:测试我们的配置
 * Spring整合junit的配置
 *      1、导入spring整合junit的jar(坐标)
 *      2、使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的
 *             @Runwith
 *      3、告知spring的运行器,spring和ioc创建是基于xml还是注解的,并且说明位置
 *         @ContextConfiguration
 *                  locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
 *                  classes:指定注解类所在地位置
 *  当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上
 * @author:Adair
 * @QQ:1578533828
 */
@SuppressWarnings("all")      // 注解警告信息
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
    // 声明AccountService业务对象
    @Autowired
    private AccountService as;
    /**
     * 测试查询所有
     */
    @Test
    public void testFindAll() {
        // 1.执行方法
        List<Account> accounts = as.findAllAccount();
        for(Account account : accounts){
            System.out.println(account);
        }
    }
    /**
     * 测试根据id查询一个
     */
    @Test
    public void testFindOne() {
        // 1.执行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }
    /**
     * 测试保存账户
     */
    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("Adair");
        account.setMoney(12345f);
        // 1.执行方法
        as.saveAccount(account);
    }
    /**
     * 测试修改账户
     */
    @Test
    public void testUpdate() {
        // 1.执行方法
        Account account = as.findAccountById(5);
        account.setMoney(23456f);
        as.updateAccount(account);
    }
    /**
     * 测试根据id删除
     */
    @Test
    public void testDelete() {
        // 1.执行方法
        as.deleteAccount(4);
    }
}

为什么不把测试类配到xml中
在解释这个问题之前,先解除大家的疑虑,配到XML中能不能用呢?
答案是肯定的,没问题,可以使用。
那么为什么不采用配置到 xml 中的方式呢?
这个原因是这样的:
第一:当我们在xml中配置了一个bean,spring加载配置文件创建容器时,就会创建对象。
第二:测试类只是我们在测试功能时使用,而在项目中它并不参与程序逻辑,也不会解决需求上的问题,所以创建完了,并没有使用。那么存在容器中就会造成资源的浪费。
所以,基于以上两点,我们不应该把测试配置到 xml 文件中。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学无止路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值