介绍&步骤
视频教程: https://www.bilibili.com/video/BV1WZ4y1P7Bp/?p=21
官方笔记链接:https://pan.baidu.com/s/1dnL5hwOPHPMNgb81yzQIOQ
提取码:2022
目录:
项目目录结构:
1.数据源的开发步骤
① 导入数据源的坐标和数据库驱动坐标
② 创建数据源对象
③ 设置数据源的基本连接数据
④ 使用数据源获取连接资源和归还连接资源
1.1导入坐标
<dependencies>
<!-- spring的坐标 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<!--导入数据源的坐标-->
<!-- C3P0连接池 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- Druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
</dependencies>
1.2创建数据源对象
这里我连接的数据库用户名是root密码为123456, 可以根据自己的用户名和密码进行改变
注意: 我这里使用的是test数据库 请确保数据库中有test数据库 不然汇报错 或者自行更换
@Test
public void testC3P0() throws PropertyVetoException, SQLException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUser("root");
dataSource.setPassword("123456");
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
@Test
public void testDruid() throws PropertyVetoException, SQLException {
ResourceBundle rb = ResourceBundle.getBundle("jdbc");
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(rb.getString("jdbc.driver"));
dataSource.setJdbcUrl(rb.getString("jdbc.url"));
dataSource.setUser(rb.getString("jdbc.username"));
dataSource.setPassword(rb.getString("jdbc.password"));
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
@Test // 读取配置文件的方法 C3PO
public void testC3P0ByProperties() throws Exception {
//加载类路径下的jdbc.properties
ResourceBundle rb = ResourceBundle.getBundle("jdbc");
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(rb.getString("jdbc.driver"));
dataSource.setJdbcUrl(rb.getString("jdbc.url"));
dataSource.setUser(rb.getString("jdbc.username"));
dataSource.setPassword(rb.getString("jdbc.password"));
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
优化: 将数据源参数弄成一个配置文件进行读取
1.3Spring配置数据源
配置jdbc.properties
文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=123456
applicationContext.xml
配置代码 导入配置文件要使用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
">
<!--用于加载配置文件jdbc.properties 默认是resource目录下面-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置数据源dataSource-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
1.4使用数据源获取连接资源和归还连接资源
java测试代码
@Test
public void testDataSource() throws PropertyVetoException, SQLException {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = (DataSource) applicationContext.getBean("dataSource");
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();// 归还资源
}
1.5知识要点
<context:property-placeholder location="xx.properties"/>
<property name="" value="${key}"/>
2.Spring注解开发
目的代替掉spring容器中的bean
介绍: 使用注解开发的目的主要是为了代替之前的applicationContext.xml
的配置文件
2.1 开启组件扫描
不配置组件扫描 写了注解也没用
<!--注解配置 主键扫描-->
<context:component-scan base-package="com.itheima"></context:component-scan>
Dao层的注解(接口和实现类)
接口:
public interface UserDao {
void save();
}
实现类:
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Value("注入普通数据")
private String str;
@Value("${jdbc.driver}")
private String driver;
@PostConstruct
public void init(){
System.out.println("init.....");
}
@PreDestroy
public void destroy(){
System.out.println("destroy......");
}
public void save() {
System.out.println(str);
System.out.println(driver);
System.out.println("save running1111.....");
}
}
Service层的注解(接口和实现类)
接口:
public interface UserService {
void save();
}
实现类:
@Service("userService")
// <bean id="userService" class="com.itheima.service.impl.UserServiceImpl"/>
public class UserServiceImpl implements UserService {
// @Resource(name = "userDao")
// <property name="userDao" ref="userDao" />
@Autowired // 按照数据类型从spring容器种进行匹配 UserDao类型 如果有多个UserDao的bean则就随机匹配不建议
@Qualifier("userDao") // value 就等于ref = value, name 的就是字段名字
private UserDao userDao;
public void save() {
userDao.save();
}
}
注意的点
2.2测试代码
@Test
public void testAnnoService(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = applicationContext.getBean(UserService.class);
userService.save();
}
3.Spring新注解开发
目的是利用java类直接代替applicationContext.xml
文件
- @Configuration
- @ComponentScan
- @Import
3.1 新键容器类和数据源配置类
新建一个数据源配置类DataSourceConfiguration
(相当于之前的dateSource Bean)
@PropertySource("classpath:jdbc.properties")
// <context:property-placeholder location="classpath:jdbc.properties"/>
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource") // id为dataSource的bean class 为放回置类型
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
新建一个配置类SpringConfiguration
(相当于之前的applicationContext.xml
配置文件)
@Configuration // 声明这是一个配置类
@ComponentScan("com.itheima") // 组件扫描
@Import({DataSourceConfiguration.class}) //导入数据源配置类
public class SpringConfiguration {
}
3.2 代码测试
AnnotationConfigApplicationContext
@Test
public void testAnnoConfiguration() throws Exception {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService userService = (UserService) applicationContext.getBean("userService");
userService.save();
DataSource dataSource = (DataSource) applicationContext.getBean("dataSource");
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
4. Spring整合Junit
目的是为了舍去这两行直接使用单元测试
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = ac.getBean("accountService",IAccountService.class);
① 导入spring集成Junit的坐标
② 使用@Runwith注解替换原来的运行期
③ 使用@ContextConfiguration指定配置文件或配置类
④ 使用@Autowired注入需要测试的对象
⑤ 创建测试方法进行测试
4.1 导入spring集成Junit的坐标
新添加的坐标
<!--此处需要注意的是,spring5 及以上版本要求 junit 的版本必须是 4.12 及以上-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
总的坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--导入数据源的坐标-->
<!-- C3P0连接池 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- Druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!--此处需要注意的是,spring5 及以上版本要求 junit 的版本必须是 4.12 及以上-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
4.2 测试方法
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(classes = {SpringConfiguration.class}) // 使用注解配置
@ContextConfiguration("classpath:applicationContext.xml") // 使用xml配置
public class SpringJunitTest {
@Autowired // 自动注入userService 如有容器中有多个userService的bean 会选择第一个进行实例化 id为空
// <bean id=" " class="com.itheima.service.impl.UserServiceImpl">
private UserService userService;
@Autowired // 自动注入DataSource 如有容器中有多个DataSource的bean 会选择第一个进行实例化
private DataSource dataSource;
@Test
public void testUserService() throws SQLException {
userService.save();
System.out.println(dataSource.getConnection());
}
}
水平有限 如有问题欢迎指正交流讨论!