Spring02:注解IOC、DBUtils单表CRUD、与Junit整合

今日内容:基于注解的IOC及IOC的案例
  • Spring中IOC的常用注解
  • 案例-使用xml方式和注解方式实现单表的CRUD操作
    • 持久层技术选型:DBUtils
  • 改造基于注解的IOC案例,使用纯注解的方式实现
    • Spring新注解的使用
  • Spring和Junit的整合
一 、Spring中IOC的常用注解
1、常用IOC注解按照作用分类
 * 注解分为四类:
 *      用于创建对象的
 *          作用与xml配置文件中编写一个bean标签<bean></bean>实现的功能相同
 *      用于注入数据的
 *          作用和xml配置文件中的bean标签写一个property标签的作用相同
 *      用于改变作用范围的
 *          作用和在bean标签中使用scope属性实现的功能相同
 *      和生命周期相关的
 *          作用和在bean标签中使用init-method和destroy-method作用相同
2、用于创建的Component注解
<?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在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为Context的名称空间和约束中-->
    <context:component-scan base-package="com.itheima"></context:component-scan>
</beans>
package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.dao.impl.AccountDaoImpl;
import com.itheima.service.IAccountService;
import org.springframework.stereotype.Component;

/**
 * 账户的业务层实现类
 *
 * 曾经的xml配置
 * <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
 *  scope="" init-method="" destroy-method="">
 *      <property name = "" value="" ref=""></property>
 *  </bean>
 *
 * 注解分为四类:
 *      用于创建对象的
 *          作用与xml配置文件中编写一个bean标签<bean></bean>实现的功能相同
 *          @Component
 *          作用:用于把当前类对象存入Spring容器中
 *          属性:
 *              value:用于指定bean的id,当我们不写时,它的默认值是当前类名,且首字母改小写
 */
@Component(value="accountService")
public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao = null;
    public AccountServiceImpl(){
        System.out.println("service对象创建了");
    }
    public void saveAccount() {
        accountDao.saveAccount();
    }
}
public class Client {
    public static void main(String[] args) {
        //1.获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象---两种方式
        IAccountService as = (IAccountService) ac.getBean("accountService");
        System.out.println(as);
    }
}
3、由Component衍生的注解
*           @Controller:一般用在表现层
 *          @Service:一般用在业务层
 *          @Repository:一般用于持久层
 *          以上三个注解的作用和属性与Component一模一样,他们三个是Spring框架为我们提供明确的三层使用的注解
 *          使三层对象更加清晰
package com.itheima.dao.impl;

import com.itheima.dao.IAccountDao;
import org.springframework.stereotype.Repository;

@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    /**
     * 账户的持久层实现类
     */
    @Override
    public void saveAccount() {
        System.out.println("保存了账户");
    }
}
public class Client {
    /**
     * 获取Spring的IOC核心容器,并根据id获取对象
     * @param args
     */
    public static void main(String[] args) {
        //1.获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象---两种方式
        IAccountService as = (IAccountService) ac.getBean("accountService");
        System.out.println(as);
        IAccountDao adao = ac.getBean("accountDao",IAccountDao.class);
        System.out.println(adao);
    }
}
4、自动按照类型注入
 *      用于注入数据的
 *          作用和xml配置文件中的bean标签写一个property标签的作用相同
 *          Autowired
 *              作用:自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
 *              位置:可以是变量上,也可以是方法上
 *              细节:在使用注解注入时,set方法就不是必须的了
5、用于注入数据的注解
 *      用于注入数据的
 *          作用和xml配置文件中的bean标签写一个property标签的作用相同
 *             @Autowired
 *              作用:自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
 *                   如果ioc容器中没有任何bean类型和要注入的变量类型匹配,则注入失败
 *                   如果ioc容器中有多个类型匹配时:
 *              位置:可以是变量上,也可以是方法上
 *              细节:在使用注解注入时,set方法就不是必须的了
 *             @Qualifier:
 *              作用:在按照类中注入的基础之上再按照名称注入。它在给类成员注入时不能注入使用
 *                    但是在给方法参数注入时可以(稍后讲)
 *               属性:
 *                  value:用于指定注入bean的id
 *             @Resource
 *               作用:直接按照bean的id注入,可以独立使用
 *               属性:
 *                  name:用于指定bean的id
 *             以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现
 *             另外:集合类型的注入只能通过xml实现
 *             @Value
 *                作用:用于注入基本类型和String类型的数据
 *                属性:
 *                  value:用于指定数据的值,它可以使用spring中的spel(也就是spring的el表达式)
 *                         SpEL的写法:${表达式}
package com.itheima.service.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.dao.impl.AccountDaoImpl;
import com.itheima.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * 账户的业务层实现类
 *
 * 注解分为四类:
 *      用于注入数据的
 *          作用和xml配置文件中的bean标签写一个property标签的作用相同
 *             @Autowired
 *              作用:自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
 *                   如果ioc容器中没有任何bean类型和要注入的变量类型匹配,则注入失败
 *                   如果ioc容器中有多个类型匹配时:
 *              位置:可以是变量上,也可以是方法上
 *              细节:在使用注解注入时,set方法就不是必须的了
 *             @Qualifier:
 *              作用:在按照类中注入的基础之上再按照名称注入。它在给类成员注入时不能注入使用
 *                    但是在给方法参数注入时可以(稍后讲)
 *               属性:
 *                  value:用于指定注入bean的id
 *             @Resource
 *               作用:直接按照bean的id注入,可以独立使用
 *               属性:
 *                  name:用于指定bean的id
 *             以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现
 *             另外:集合类型的注入只能通过xml实现
 *             @Value
 *                作用:用于注入基本类型和String类型的数据
 *                属性:
 *                  value:用于指定数据的值,它可以使用spring中的spel(也就是spring的el表达式)
 *                         SpEL的写法:${表达式}
 */
@Service(value="accountService")
public class AccountServiceImpl implements IAccountService {
    @Autowired
    @Qualifier("accountDao1")
    //@Resource(name="accountDao2")
    private IAccountDao accountDao = null;
    public void saveAccount() {
        accountDao.saveAccount();
    }
}
6、改变作用范围以及和生命周期相关的注解
package com.itheima.service.impl;
/**
 * 账户的业务层实现类
 *
 * 注解分为四类:
 *      用于改变作用范围的
 *          作用和在bean标签中使用scope属性实现的功能相同
 *          Scope
 *              作用:用于指定bean的作用范围
 *              属性:
 *                  value:指定范围的取值。常用取值:singleton prototype,默认单例singleton
 *      和生命周期相关的【了解】
 *          作用和在bean标签中使用init-method和destroy-method作用相同
 *          PreDestroy
 *              作用:用于指定销毁方法
 *          PostConstruct
 *              作用:用于指定初始化方法
 */
@Service(value="accountService")
//@Scope("single")
public class AccountServiceImpl implements IAccountService {
    //@Autowired
    //@Qualifier("accountDao1")
    @Resource(name="accountDao2")
    private IAccountDao accountDao = null;
    @PostConstruct
    public void init() {
        System.out.println("初始化方法执行了");
    }
    @PreDestroy
    public void destroy() {
        System.out.println("销毁方法执行了");
    }
    public void saveAccount() {
        accountDao.saveAccount();
    }
}
package com.itheima.ui;
import com.itheima.dao.IAccountDao;
import com.itheima.service.IAccountService;
import com.itheima.service.impl.AccountServiceImpl;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
/**
 *
 */
public class Client {
    /**
     * 获取Spring的IOC核心容器,并根据id获取对象
     * Application的三个常用实现类
     *      ClassPathXmlApplicationContext:可以加载类路径下的配置文件,要求配置文件必须在类路径下,不在的加载不了
     *      FileSystemApplicationContext:可以加载磁盘任意路径下的配置文件(必须有访问权限)
     *      AnnotationConfigApplicationContext:是用于读取注解创建容器的,为明天的内容
     * @param args
     */
    public static void main(String[] args) {
        //1.获取核心容器对象
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象---两种方式
        IAccountService as = (IAccountService) ac.getBean("accountService");
        IAccountService as2 = (IAccountService) ac.getBean("accountService");
        /*System.out.println(as);
        IAccountDao adao = ac.getBean("accountDao",IAccountDao.class);
        System.out.println(adao);*/
        //System.out.println(as==as2);
        as.saveAccount();
        ac.close();
    }
}
二、案例-使用xml方式和注解方式实现单表的CRUD操作
1、XMLIOC的案例-准备案例的必须代码
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 runner;

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

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

    @Override
    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);//相当于return
        }
    }

    @Override
    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);//相当于return
        }
    }

    @Override
    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);//相当于return
        }
    }

    @Override
    public void deleteAccount(Integer accountId) {
        try {
            runner.update("delete from account where id = ?",accountId);
        } catch (Exception e) {
            throw new RuntimeException(e);//相当于return
        }
    }
}
2、XMLIOC案例-编写spring的Ioc配置
<?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.itheima.service.impl.AccountServiceImpl">
        <!-- 注入dao对象 -->
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    <!--配置dao对象-->
    <bean id="accountDao" class="com.itheima.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/eesy"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
</beans>
3、测试基于XML的IOC案例
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() {
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        //2.执行方法
        List<Account> accounts = as.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }

    }
    @Test
    public void testFindOne() {
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        //2.执行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }
    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("johann");
        account.setMoney(500.0f);
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        //2.执行方法
        as.saveAccount(account);

    }
    @Test
    public void testUpdate() {
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        //2.执行方法
        Account account = as.findAccountById(1);
        account.setMoney(256f);
        as.updateAccount(account);
    }
    @Test
    public void testDelete() {
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        //2.执行方法
        as.deleteAccount(4);
    }
}
4、把自己编写的类使用注解配置
注解的配置文件:xmls:context
<?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.itheima"></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.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
</beans>
/**
 * 账户的业务层实现类
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    //唯一的对象在容器中,使用autowired实现自动注入
    @Autowired
    private IAccountDao accountDao;

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }
/**
 * 账户的持久层实现类
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private QueryRunner runner;
三、Spring的新注解
1、spring的新注解-Configuration和ComponentScan
之前存在的问题:
  • 测试类中存在的重复代码
  • 非自定义类中QueryRunner无法注入
  • 创建容器扫描包
package config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * 该类是一个配置类,其作用和bean.xml作用相同
 * Spring中的新注解
 * Configuration
 *      作用:指定当前类是是一个配置类
 * ComponentScan
 *      作用:用于通过注解指定spring在创建容器时要扫描的包
 *      value属性和basePackages的作用相同,都是用于指定创建容器时要扫描的包
 *           我们使用此注解就等同于在xml中配置了
 * <context:component-scan base-package="com.itheima"></context:component-scan>
 *
 */
@Configuration
@ComponentScan(basePackages = "com.itheima")//类路径,内容是一个数组,可以写{xxx,xxx}或xxx
public class SpringConfiguration {

}
2、spring的新注解-Bean
可以通过调用构造函数实例化
不看属性prototype,则与bean标签作用不相同
bean中有容器中的key和value,需要注解将返回值存入spring容器中
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 javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * 该类是一个配置类,其作用和bean.xml作用相同
 * Spring中的新注解
 * Configuration
 *      作用:指定当前类是是一个配置类
 * ComponentScan
 *      作用:用于通过注解指定spring在创建容器时要扫描的包
 *      value属性和basePackages的作用相同,都是用于指定创建容器时要扫描的包
 *           我们使用此注解就等同于在xml中配置了
 * <context:component-scan base-package="com.itheima"></context:component-scan>
 * Bean
 *      作用:用于把当前方法的返回值作为bean对象存入spring的IOC容器中
 *      属性:
 *          name:用于指定bean的id,当不写时默认值是当前方法的名称
 *      细节:
 *          当使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象
 *          查找的方式和AutoWired是一样的,查找类型匹配,一个 ,没有,多个
 *
 *     <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="root"></property>
 *     </bean>
 */
@Configuration
@ComponentScan(basePackages = "com.itheima")//类路径,内容是一个数组,可以写{xxx,xxx}或xxx
public class SpringConfiguration {
    /**
     * 用于创建一个QueryRunner对象
     * @param dataSource
     * @return
     */
    @Bean(name="runner")//相当于bean的id
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源 对象
     */
    @Bean(name="dataSource")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("");
            ds.setJdbcUrl("");
            ds.setUser("");
            ds.setPassword("");
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
3、AnnotationConfigApplicationContext的使用
test方法仍使用了bean.xml
package com.itheima.test;

import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import config.SpringConfiguration;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
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");
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        //2.执行方法
        List<Account> accounts = as.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }

    }
    @Test
    public void testFindOne() {
        //1.获取容器
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        //2.执行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }
    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("johann");
        account.setMoney(500.0f);
        //1.获取容器
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        //2.执行方法
        as.saveAccount(account);

    }
    @Test
    public void testUpdate() {
        //1.获取容器
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        //2.执行方法
        Account account = as.findAccountById(1);
        account.setMoney(256f);
        as.updateAccount(account);
    }
    @Test
    public void testDelete() {
        //1.获取容器
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        //2.执行方法
        as.deleteAccount(4);
    }
}
4、spring的新注解-Import
 * Configuration
 *      作用:指定当前类是是一个配置类
 *      细节:当配置类作为AnnotationCofigApplicationContext对象创建的参数时,该注解可以不写
package config;

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

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
/**
 * Import
 *      作用:用于导入其他的配置类
 *      属性:
 *          value:用于指定其他配置类的字节码
 *                 当使用import注解之后,有import注解的类就是父配置类,而导入的都是子配置类
 *
 *
 */
//@Configuration
@ComponentScan({"com.itheima"})//类路径,内容是一个数组,可以写{xxx,xxx}或xxx
@Import(JdbcConfig.class)
public class SpringConfiguration {
    //期望是公共配置,而不是只配置连接数据库的
}
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.Configuration;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;

/**
 * 和Spring连接数据库相关的配置类
 */
//@Configuration
public class JdbcConfig {
    /**
     * 用于创建一个QueryRunner对象
     * @param dataSource
     * @return
     */
    @Bean(name="runner")//相当于bean的id
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源 对象
     */
    @Bean(name="dataSource")
    @Scope("prototype")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy");
            ds.setUser("root");
            ds.setPassword("root");
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
public class AccountServiceTest {
    @Test
    public void testFindAll() {
        //1.获取容器
        //ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.
        // class,JdbcConfig.class);可以不写Configuration注解
        //成为并列关系,不希望写这么多class
        //需要加注解和扫描的包

        //2.得到业务层对象
        IAccountService as = ac.getBean("accountService",IAccountService.class);
        //2.执行方法
        List<Account> accounts = as.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }
5、spring的新注解-PropertySource
package config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
/**
 * PropertySource
 *      作用:用于导入其他的配置类
 *      属性:
 *          value:指定文件的名称和路径
 *              关键字:classpath表示类路径下
 *              有包:config/itheima/xxx
 *
 */
//@Configuration
@ComponentScan({"com.itheima"})//类路径,内容是一个数组,可以写{xxx,xxx}或xxx
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
    //期望是公共配置,而不是只配置连接数据库的
}
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.Scope;

import javax.sql.DataSource;

/**
 * 和Spring连接数据库相关的配置类
 */
//@Configuration
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")//相当于bean的id
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源 对象
     */
    @Bean(name="dataSource")
    @Scope("prototype")
    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);
        }
    }
}
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy
jdbc.username=root
jdbc.password=root
这种方式更加复杂
建议使用xml配置或注解同时使用
原则:实际开发中,哪个方便选哪种
6、Qualifier注解的另一种用法
一个对象有多个实现类时,需要修改方法参数,添加Qualifier注解,可以独立使用
package 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连接数据库相关的配置类
 */
//@Configuration
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")//相当于bean的id
    @Scope("prototype")
    //Qualifier给类路径注入时,需要和autowired匹配,
    //给参数注入时,不需要和wutowired匹配
    public QueryRunner createQueryRunner(@Qualifier("ds1") DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源 对象
     */
    @Bean(name="ds0")//优先选runner的形参
    @Scope("prototype")
    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);
        }
    }
    //有多个数据源
    @Bean(name="ds1")
    @Scope("prototype")
    public DataSource createDataSource1(){
        try {
            //希望读取配置文件
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy02");
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
四、Spring整合Junit
1、spring整合junit问题分析
  • 应用程序的入口(main方法)
  • Junit单元测试中,没有main方法也能执行
    • 实际上,Junit集成了一个main方法
    • 该方法会判断当前测试类中哪些方法有 @Test注解
    • Junit注解就会有test注解的方法执行
  • Junit不会管是否使用 Spring框架
    • 在执行测试方法时,Junit根本不知道 
2、spring整合junit完成
/**
 * 使用Junit单元测试:测试我们的配置
 * Spring整合Junit的配置
 *    1、导入Spring整合Junit的坐标
 *    2、使用Junit提供的一个注解把原有的main方法替换成Spring提供的
 *      @Runwith
 *    3、告知Spring的运行期,Spring和IOC创建是基于xml还是注解的,并且说明位置
 *      @ContextConfiguration
 *          locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
 *          classes:指定注解类所在的位置
 *          当使用Spring5.x版本时,要求Junit的jar包必须是4.1.2及以上
 */
@RunWith(SpringJUnit4ClassRunner.class) //相当于main方法,自动调用test类
@ContextConfiguration(classes=SpringConfiguration.class) //配置文件
public class AccountServiceTest {
    //private ApplicationContext ac;
    @Autowired //自动注入
    private IAccountService as = null;
    @Test
    public void testFindAll() {
        //2.执行方法
        List<Account> accounts = as.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }
package config;

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

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * 该类是一个配置类,其作用和bean.xml作用相同
 * Spring中的新注解
 * Configuration
 *      作用:指定当前类是是一个配置类
 *      细节:当配置类作为AnnotationCofigApplicationContext对象创建的参数时,该注解可以不写
 * ComponentScan
 *      作用:用于通过注解指定spring在创建容器时要扫描的包
 *      value属性和basePackages的作用相同,都是用于指定创建容器时要扫描的包
 *           我们使用此注解就等同于在xml中配置了
 * <context:component-scan base-package="com.itheima"></context:component-scan>
 * Bean
 *      作用:用于把当前方法的返回值作为bean对象存入spring的IOC容器中
 *      属性:
 *          name:用于指定bean的id,当不写时默认值是当前方法的名称
 *      细节:
 *          当使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象
 *          查找的方式和AutoWired是一样的,查找类型匹配,一个 ,没有,多个
 *
 *     <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="root"></property>
 *     </bean>
 * Import
 *      作用:用于导入其他的配置类
 *      属性:
 *          value:用于指定其他配置类的字节码
 *                 当使用import注解之后,有import注解的类就是父配置类,而导入的都是子配置类
 * PropertySource
 *      作用:用于导入其他的配置类
 *      属性:
 *          value:指定文件的名称和路径
 *              关键字:classpath表示类路径下
 *              有包:config/itheima/xxx
 *
 */
//@Configuration
@ComponentScan({"com.itheima"})//类路径,内容是一个数组,可以写{xxx,xxx}或xxx
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
    //期望是公共配置,而不是只配置连接数据库的
}





posted @ 2021-02-16 21:26  哥们要飞  阅读(119)  评论(0)    收藏  举报