SSM——Spring(2)
SSM——Spring(2)
一、Spring配置数据源
1.1 数据源(连接池)的作用
数据源(连接池)是提高程序性能如出现的。
事先实例化数据源,初始化部分连接资源。
使用连接资源时从数据源中获取。
使用完毕后将连接资源归还给数据源。
常见的数据源(连接池):DBCP、C3P0、BoneCP、Druid等。
1.2 数据源的开发步骤
- 导入数据源的坐标和数据库驱动坐标。
- 创建数据源对象。
- 设置数据源的基本连接数据。
- 使用数据源获取连接资源和归还连接资源。
- 导入c3p0和druid的坐标。

- 导入MySQL数据库驱动坐标。

- 创建C3P0连接池。

- 创建Druid连接池。

- 提取jdbc.properties配置文件。

- 读取
jdbc.properties
配置文件创建连接池。

1.3 Spring配置数据源
- 可以将DataSource的创建权交由Spring容器去完成。
- DataSource有无参构造方法,而Spring默认就是通过无参构造方法实例化对象的。
- DataSource要想使用需要通过set方法设置数据库连接信息,而Spring可以通过set方法进行字符串注入。

- 测试从容器当中获取数据源。

1.4 抽取JDBC配置文件
applicationContext.xml
加载jdbc.properties
配置文件获得连接信息。首先,需要引入context命名空间和约束路径:
- 命名空间:
xmlns:context="http://www.springframework.org/schema/context"
- 约束路径:
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
。
- 命名空间:

二、Spring注解开发
- Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率。
- Spring原始注解主要是替代
<Bean>
的配置。

- 使用注解进行开发时,需要在
applicationContext.xml
中配置组件扫描,作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法。

- 使用@Compont或@Repository标识UserDaoImpl需要Spring进行实例化。

- 使用@Compont或@Service标识UserServiceImpl需要Spring进行实例化,使用@Autowired或者@Autowired+@Qulifier或者@Resource进行userDao的注入。

- 使用@Value进行字符串的注入。

- 使用@Scope标注Bean的范围。

- 使用@PostConstruct标注初始化方法,使用@PreDestroy标注销毁方法。

- 使用上面的注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下。


- @Configuration和@ComponentScan和@Import。

- @PropertySource和@value。

- @Bean。

- 测试加载核心配置类创建Spring容器。

三、Spring整合Junit
3.1 原始Junit测试Spring的问题
- 在测试类中,每个测试方法都有以下两行代码。这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。
3.2 上述问题解决方法
- 让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉它。将需要进行测试Bean直接在测试类中进行注入。
3.3 Spring集成Junit步骤

- 导入spring集成Junit的坐标。

- 使用@Runwith注解替换原来的运行期。

- 使用@ContextConfiguration指定配置文件或配置类。

- 使用@Autowired注入需要测试的对象。

- 创建测试方法进行测试。

All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.