从前用基于xml的QueryRunner注入

@Autowired
private QueryRunner runner;
<?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"></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/easy?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT%2B8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

</beans>

改用配置类之后

  • 配置类
@ComponentScan("com")
public class SpringConfiguration {
    /**
     * 用于创建一个QueryRunner对象
     *
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource) {
        return new QueryRunner(dataSource);
    }

    @Bean(name = "dataSource")
    public DataSource createDataSource() {
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("com.mysql.cj.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/easy?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8");
            ds.setUser("root");
            ds.setPassword("1809227959");
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
  • 测试使用 AnnotationConfigApplicationContext
@Test
public void testFindAll() {
    //1.获取容易
    ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
    //2.得到业务层对象
    IAccountService as = ac.getBean("accountService", IAccountService.class);
    //3.执行方法
    List<Account> accounts = as.findAllAccount();
    for (Account account : accounts) {
        System.out.println(account);
    }
}

配置类的高级实现

  • 注解解释
Configuration:
     作用:指定当前类是一个配置类
     细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。

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注解的作用是一样的

Import:
      作用:用于导入其他的配置类
      属性:
          value:用于指定其他配置类的字节码。
                 当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类

PropertySource:
      作用:用于指定properties文件的位置
      属性:
          value:指定文件的名称和路径。
                  关键字:classpath,表示类路径下
  • SpringConfiguration.java
@ComponentScan("com")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
    
}
  • JdbcConfig.java
/**
 * 和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(@Qualifier("ds2") 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);
        }
    }

    @Bean(name="ds1")
    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);
        }
    }
}
  • resources文件夹下jdbcConfig.properties
jdbc.driver=com.cj.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/easy?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=1809227959

spring整合Junit单元测试

  • 导入jar包
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.5.RELEASE</version>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
</dependency>
  • 测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {

    @Autowired
    private IAccountService as = null;
    
    @Test
    public void testFindOne() {
        Account account = as.findAccountById(1);
        System.out.println(account);
    }
    
}


hhhhh