spring 笔记二 spring配置数据源和整合测试功能

Spring配置数据源

数据源(连接池)的作用

• 数据源(连接池)是提高程序性能如出现的
• 事先实例化数据源,初始化部分连接资源
• 使用连接资源时从数据源中获取
• 使用完毕后将连接资源归还给数据源

常见的数据源(连接池):DBCP、C3P0、BoneCP、Druid

数据源的开发步骤
① 导入数据源的坐标和数据库驱动坐标
② 创建数据源对象
③ 设置数据源的基本连接数据
④ 使用数据源获取连接资源和归还连接资源

数据源的手动创建

①导入druid的坐标

<!--数据源--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.16</version></dependency>

① 导入mysql数据库驱动坐标

  <!-- 数据库驱动相关依赖--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency>

② 创建Druid连接池

@Testpublic void testDruid() throws Exception {//创建数据源
DruidDataSource dataSource = new DruidDataSource();//设置数据库连接参数
dataSource.setDriverClassName("com.mysql.jdbc.Driver");dataSource.setUrl("jdbc:mysql://localhost:3306/test");dataSource.setUsername("root");dataSource.setPassword("root");//获得连接对象
Connection connection = dataSource.getConnection();System.out.println(connection);}

③ 提取jdbc.properties配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

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

@Testpublic void testC3P0ByProperties() throws Exception {//加载类路径下的jdbc.propertiesResourceBundle 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);}

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

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="com.mysql.jdbc.Driver"/><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/><property name="user" value="root"/><property name="password" value="root"/></bean>

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

ApplicationContext applicationContext = new 
ClassPathXmlApplicationContext("applicationContext.xml");DataSource dataSource = (DataSource) 
applicationContext.getBean("dataSource");Connection connection = dataSource.getConnection();System.out.println(connection);

抽取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

 <context:property-placeholder location="classpath:jdbc.properties"/>
<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>

Spring注解

Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率

  • 使用@Compont或@Repository标识UserDaoImpl需要Spring进行实例化
//@Component("userDao")@Repository("userDao")public class UserDaoImpl implements UserDao {@Overridepublic void save() {System.out.println("save running... ...");}}
  • 使用@Compont或@Service标识UserServiceImpl需要Spring进行实例化
  • 使用@Autowired或者@Autowired+@Qulifier或者@Resource进行userDao的注入
//@Component("userService")@Service("userService")public class UserServiceImpl implements UserService {/*@Autowired@Qualifier("userDao")*/@Resource(name="userDao")private UserDao userDao;@Overridepublic void save() {userDao.save();}}
  • 使用@Value进行字符串的注入
@Repository("userDao")public class UserDaoImpl implements UserDao {@Value("注入普通数据")private String str;@Value("${jdbc.driver}")private String driver;@Overridepublic void save() {System.out.println(str);System.out.println(driver);System.out.println("save running... ...");}}
  • 使用@Scope标注Bean的范围
//@Scope("prototype")@Scope("singleton")public class UserDaoImpl implements UserDao {//此处省略代码
}
  • 使用@PostConstruct标注初始化方法,使用@PreDestroy标注销毁方法
@PostConstructpublic void init(){System.out.println("初始化方法....");}@PreDestroypublic void destroy(){System.out.println("销毁方法.....");}

Spring注解

使用上面的注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下:
 非自定义的Bean的配置:<bean>
 加载properties文件的配置:<context:property-placeholder>
 组件扫描的配置:<context:component-scan>
 引入其他文件:<import>

注解说明
@Configuration用于指定当前类是一个Spring 配置类,当创建容器时会从该类上加载注解
@ComponentScan用于指定Spring 在初始化容器时要扫描的包。作用和在Spring 的xml 配置文件中的 <context:component-scan base-package=“com.onenewcode”/>一样
@Bean使用在方法上,标注将该方法的返回值存储到Spring 容器中
@PropertySource用于加载.properties 文件中的配置
@Import用于导入其他配置类
  • @Configuration
  • @ComponentScan
  • @Import
 @Configuration@ComponentScan("com.onenewcode")@Import({DataSourceConfiguration.class})public class SpringConfiguration {}
  • @PropertySource
  • @value
@PropertySource("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
@Bean(name="dataSource")public DataSource getDataSource() throws PropertyVetoException {ComboPooledDataSource dataSource = new ComboPooledDataSource();dataSource.setDriverClass(driver);dataSource.setJdbcUrl(url);dataSource.setUser(username);dataSource.setPassword(password);return dataSource;}

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


@Testpublic 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);}

Spring整合Junit

原始Junit测试Spring的问题

在测试类中,每个测试方法都有以下两行代码:

ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");IAccountService as = ac.getBean("accountService",IAccountService.class);

这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。

上述问题解决思路
• 让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉它
• 将需要进行测试Bean直接在测试类中进行注

Spring集成Junit步骤

① 导入spring集成Junit的坐标
② 使用@Runwith注解替换原来的运行期
③ 使用@ContextConfiguration指定配置文件或配置类
④ 使用@Autowired注入需要测试的对象
⑤ 创建测试方法进行测试

<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.2.8.RELEASE</version></dependency>

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

@RunWith(SpringJUnit4ClassRunner.class)public class SpringJunitTest {}

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

@RunWith(SpringJUnit4ClassRunner.class)//加载spring核心配置文件
//@ContextConfiguration(value = {"classpath:applicationContext.xml"})//加载spring核心配置类
@ContextConfiguration(classes = {SpringConfiguration.class})public class SpringJunitTest {}

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

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = {SpringConfiguration.class})public class SpringJunitTest {@Autowiredprivate UserService userService;}

⑤创建测试方法进行测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
@Test
public void testUserService(){
userService.save();
}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/217287.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

STM32——串口实验(非中断)

需求&#xff1a; 接受串口工具发送的字符串&#xff0c;并将其发送回串口工具。 硬件接线&#xff1a; TX -- A10 RX -- A9 一定要记得交叉接线&#xff01;&#xff01; 串口配置&#xff1a; 1. 选定串口 2. 选择模式 异步通讯 3. 串口配置 4. 使用MicroLIB库 从…

(第27天)Oracle 数据泵转换分区表

在Oracle数据库中,分区表的使用是很常见的,使用数据泵也可以进行普通表到分区表的转换,虽然实际场景应用的不多。 创建测试表 sys@ORADB 2022-10-13 11:54:12> create table lucifer.tabs as select * from dba_objects;Table created.sys

应用服务器:负责处理逻辑的服务器 “ 应用服务器怎么处理逻辑?

应用服务器是指通过各种协议把商业逻辑曝露给客户端的程序。它提供了访问商业逻辑的途径以供客户端应用程序使用。应用服务器使用此商业逻辑就像调用对象的一个方法一样。 应用服务器的工作过程包括以下步骤&#xff1a; 1、客户端发送请求&#xff1a;当客户端需要访问应用程…

harmonyOS HTTP数据请求能用类

通用类 import http from ohos.net.http;// 调试开关 const Test: boolean true;// API 地址 const Url: string Test ? http://api.林.cn/ : http://api.林.cn/;export function request(api: string, method: string, data: any, token: string ): Promise<any> {…

Linux下的网络服务

一般来说&#xff0c;各种操作系统在网络方面的性能比较是这样的顺序BSD>Linux>Win NT>Win 9X, 由此说来&#xff0c;Linux的网络功能仅次于UNIX&#xff0c;而强于Win NT和其它的视窗系列产品&#xff0c;对于Win2000我还不能评价太多&#xff0c;因为不是很熟。 Lin…

Android audio设置投屏和喇叭双输出

业务场景&#xff1a; 在 Android13 平台上&#xff0c;使用 USB 投屏工具scrcpy&#xff0c;投屏到电脑端时&#xff0c;声音被截到 电脑端播放&#xff0c;Android设备 端静音&#xff0c;在Android11及之前都是 在Android设备端正常播放。 分析&#xff1a; scrcpy 支持 …

数据结构 | 大根堆

思维导图 代码 #include<stdio.h> #include<iostream> using namespace std; void HeapAdjust(int* arr, int start, int end) {int temp arr[start];for (int i 2 * start 1; i < end; i 2 * i 1) //end可以取到等于 因为它是最后一个元素{if (i<end…

Spring boot注解

1.RestController RestController 注解用于标识一个类,表示该类的所有方法都返回JSON或XML响应&#xff0c;而不是视图页面。它是Controller和ResponseBody的组合 2.RequestMapping RequestMapping 注解用于映射HTTP请求到控制器方法或类。它可以用于类级别和方法级别,用于定…

UI5 development on VS Studio code

今天来分享一下如何VS studio code 上UI5开发环境的搭建 1.安装Node.js 路径&#xff1a;Node.js 因安装步骤较为简单&#xff0c;故不在此赘述。 验证方法如下&#xff1a;WINR-->CMD--->node --version 出现下图即可 2. 安装UI5 CLI (为了后面我们方便使用UI5 的命令…

向ChatGPT提特殊问题,可提取原始训练数据!

随着ChatGPT等模型的参数越来越大&#xff0c;预训练数据也呈指数级增长。谷歌DeepMind、华盛顿大学、康奈尔大学等研究人员发现,无论是开源还是闭源模型&#xff0c;在训练过程中皆能记住一定数量的原始训练数据样本。 如果使用特定的恶意攻击&#xff0c;便能轻松地从模型中…

python pip 相关缓存清理(windows+linux)

pip会大量缓存&#xff0c;如果全部堆在系统盘&#xff0c;会造成别的无法使用 windows和linux通用 一、linux linux是在命令行操作 1.查看缓存位置 pip cache dir我这里默认是在/root/.cache/pip 2.查看大小 du -sh /root/.cache/pip结果如下&#xff1a; 3.清理&#…

Redis的四种部署模式:原理、优缺点及应用场景

Redis是一款高性能的开源NoSQL数据库&#xff0c;它支持多种数据结构&#xff0c;如字符串、列表、集合、散列、有序集合等。Redis的主要特点是将所有数据存储在内存中&#xff0c;实现了极高的读写速度&#xff0c;同时也提供了持久化机制&#xff0c;保证了数据的安全性和一致…

深入理解 Go Channel:解密并发编程中的通信机制

一、Channel管道 1、Channel说明 共享内存交互数据弊端 单纯地将函数并发执行是没有意义的。函数与函数间需要交互数据才能体现编发执行函数的意义虽然可以使用共享内存进行数据交换&#xff0c;但是共享内存在不同的goroutine中容易发送静态问题为了保证数据交换的正确性&am…

Windows的C盘爆掉了怎么办?

本文参考&#xff1a; C盘太满怎么办&#xff1f;亲测8种好用方法&#xff01; 如果C盘的分区爆掉了&#xff0c;变红色了&#xff0c;是时候该处理这个问题了&#xff0c;解决你的C盘焦虑&#xff01; 第一招&#xff1a;删除C盘文件 首先你会想到清理C盘里面的文件&#x…

数据结构之----数组、链表、列表

数据结构之----数组、链表、列表 什么是数组&#xff1f; 数组是一种线性数据结构&#xff0c;它将相同类型的元素存储在连续的内存空间中。 我们将元素在数组中的位置称为该元素的索引。 数组常用操作 1. 初始化数组 我们可以根据需求选用数组的两种初始化方式&#xff…

机器视觉系统选型-同轴光源分类及应用场景

同轴光源 从与相机同轴的方向均匀照射漫射光 Mark点定位条码识别二维码识别反光物体表面缺陷检测 高亮同轴光源 照射光线与水平方向成低角度夹角Mark点定位反光件表面凹坑、损伤、缺陷印刷电路板二维码识别 平行同轴光源 从与相机同轴方向照射平行度高 的平行光尺寸测量玻璃检…

【图像处理】图像骨架化提取c++实现

以下代码是对图像进行骨架提取的函数&#xff1a; void thinImage(cv::Mat& src, int maxIterations) {assert(src.type() CV_8UC1);cv::Mat dst(src.size(), src.type());int width src.cols;int height src.rows;for (int i 0; i < height; i){uchar* ptr src.p…

团队git操作流程

项目的开发要求 项目组厉员每天代码提交不少于20次企业项目开发代码的每天的提交一般提交3-5次代码仓库的管理 git的基础操作流程 命令模式 git push插件模式 vscode git graphGUI软件管理模式 sourcetree git在项目团队化开发中的应用 master(一般是不动的)dev (主要是拿…

2. 如何通过公网IP端口映射访问到设备的vmware虚拟机的ubuntu服务器

文章目录 1. 主机设备是Windows 11系统2. 安装vmware虚拟机3. 创建ubuntu虚拟机&#xff08;据说CentOS 7 明年就不维护了&#xff0c;就不用这个版本的linux了&#xff09;4. 安装nginx服务:默认端口805. 安装ssh服务:默认端口226. 设置主机 -> ubuntu的端口映射7. 设置路由…

【Amis Low Code 结合FastAPI进行前端框架开发】

官方文档 封装思想 直接复制官网json数据即可开发每个json中的接口由fastapi 转发&#xff08;透传&#xff09;使其开发模式与前端思维一致 基础组件 from amis import Page, Service, App from pydantic import BaseModel, Field from fastapi import FastAPI, Request, …