Spring配置数据源
数据源(连接池)的作用
- 数据源(连接池)可以提高程序性能
- 事先实例化数据源,初始化部分连接资源
- 使用连接资源时从数据源中获取
- 使用完毕后将连接资源归还给数据源
常见的数据源(连接池):DBCP、C3P0、BoneCP、Druid等
数据源的开发步骤
- 导入数据源的坐标和数据库驱动坐标
- 创建数据源对象
- 设置数据源的基本连接数据
- 使用数据源获取连接资源和归还连接资源
在pom.xml中导入数据库驱动和数据源坐标
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 | <dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.32</version>
    </dependency>
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.10</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
</dependencies>
 | 
 
创建数据源对象,设置数据源的基本连接数据,使用数据源获取连接资源和归还连接资源
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
 | public class DataSourceTest {
    @Test
    // 测试手动创建c3p0数据源
    public void test1() throws Exception {
        // 创建数据源对象
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        // 设置数据源的基本连接数据
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUser("root");
        dataSource.setPassword("123");
        // 使用数据源获取连接资源
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        // 归还连接资源
        connection.close();
    }
}
 | 
 
为了使具体字符串设置与数据源解耦合,我们可以抽取jdbc.properties配置文件
具体代码可见个人GitHub仓库
用Spring配置数据源
可以将DataSource的创建权交由Spring容器去完成
在pom.xml导入Spring坐标
| 1
2
3
4
5
6
 | <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.5.RELEASE</version>
    <scope>test</scope>
</dependency>
 | 
 
在xml配置文件中通过set方法进行字符串注入
| 1
2
3
4
5
6
 | <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/test"></property>
    <property name="user" value="root"></property>
    <property name="password" value="123"></property>
</bean>
 | 
 
抽取jdbc配置文件
applicationContext.xml加载jdbc.properties配置文件获得连接信息。
jdbc.properties中配置数据源的基本连接数据:
| 1
2
3
4
 | jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=123
 | 
 
首先,需要在applicationContext.xml引入context命名空间和约束路径:
- 命名空间:xmlns:context="http://www.springframework.org/schema/context"
- 约束路径:http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
然后,配置xml文件,在Spring容器中加载properties文件
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
 | <!--加载外部的properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <!--SPEL表达式获取properties配置文件中的值-->
    <property name="driverClass" value="${jdbc.driver}"></property>
    <property name="jdbcUrl" value="${jdbc.url}"></property>
    <property name="user" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>
</bean>
 | 
 
最后,编写测试方法test4(),测试是否能够连接数据库:
|  1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
 | public class DataSourceTest {
    @Test
    // 测试Spring容器产生c3p0数据源对象
    public void test4() throws Exception {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource dataSource = applicationContext.getBean(DataSource.class);
        // 使用数据源获取连接资源
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        // 归还连接资源
        connection.close();
    }
}
 | 
 
Spring注解开发
Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率
Spring注解主要用于替代xml中的配置
| 注解 | 说明 | 
| @Component | 使用在类上用于实例化Bean | 
| @Controller | 使用在web层类上用于实例化Bean | 
| @Service | 使用在service层类上用于实例化Bean | 
| @Repository | 使用在dao层类上用于实例化Bean | 
| @Autowired | 使用在字段上用于根据类型依赖注入 | 
| @Qualifier | 结合@Autowired一起使用用于根据名称进行依赖注入 | 
| @Resource | 相当于@Autowired+@Qualifier,按照名称进行注入 | 
| @Value | 注入普通属性,可以结合 .properties文件使用 | 
| @Scope | 标注Bean的作用范围 | 
| @PostConstruct | 使用在方法上标注该方法是Bean的初始化方法 | 
| @PreDestroy | 使用在方法上标注该方法是Bean的销毁方法 | 
| @Configuration | 用于指定当前类是一个 Spring 配置类,当创建容器时会从该类上加载注解 | 
| @ComponentScan | 用于指定 Spring 在初始化容器时要扫描的包。作用和在 Spring 的 xml配置文件中的<context:component-scan base-package="com.wyatt"/>一样 | 
| @Bean | 使用在方法上,标注将该方法的返回值存储到 Spring 容器中 | 
| @PropertySource | 用于加载 .properties文件中的配置 | 
| @Import | 用于导入其他配置类 | 
组件扫描:作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法
Spring集成Junit
原始Junit测试Spring时,在测试类中,每个测试方法都有以下两行代码:
| 1
2
 | ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = app.getBean(UserService.class);
 | 
 
这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。
为了简化代码,Spring集成了Junit
- 让Spring-test负责创建Spring容器,但是需要将配置文件的名称告诉它
- 将需要进行测试Bean直接在测试类中进行注入
Spring集成Junit步骤:
- 导入spring-test的坐标
- 使用@Runwith注解替换原来的运行期
- 使用@ContextConfiguration指定配置文件或配置类
- 使用@Autowired注入需要测试的对象
- 创建测试方法进行测试
Spring JdbcTemplate基本使用
JdbcTemplate是spring框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装。
spring框架为我们提供了很多的操作模板类:
- 操作关系型数据库的JdbcTemplate和HibernateTemplate
- 操作nosql数据库的RedisTemplate
- 操作消息队列的JmsTemplate
JdbcTemplate开发步骤:
- 导入spring-jdbc和spring-tx坐标
- 创建数据库表和实体
- 创建JdbcTemplate对象
| 1
2
 | JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
 | 
 
| 1
2
3
4
5
 | // 更新操作
jdbcTemplate.update (sql,params);
// 查询操作
jdbcTemplate.query (sql,Mapper,params);
jdbcTemplate.queryForObject(sql,Mapper,params);
 |