spring2

1.Spring配置数据源

1.1 数据源(连接池)的作用

数据源(连接池)是提高程序性能如出现的

事先实例化数据源,初始化部分连接资源

使用连接资源时从数据源中获取

使用完毕后将连接资源归还给数据源

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

开发步骤

①导入数据源的坐标和数据库驱动坐标

②创建数据源对象

③设置数据源的基本连接数据

④使用数据源获取连接资源和归还连接资源

1.2 数据源的手动创建

①导入c3p0和druid的坐标

<!-- 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>8.0.30</version>
    </dependency>
<!-- mysql驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.39</version>
</dependency>

②创建C3P0连接池

@Test
public void testC3P0() throws Exception {
    //创建数据源
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    //设置数据库连接参数
    dataSource.setDriverClass("com.mysql.jdbc.Driver");                                    dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
    dataSource.setUser("root");
    dataSource.setPassword("root");
    //获得连接对象
    Connection connection = dataSource.getConnection();
    System.out.println(connection);
}

②创建Druid连接池

@Test
public 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.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test_spring
jdbc.username=root
jdbc.password=123321

我的配置:

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

@Test
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.3 Spring配置数据源

可以将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);

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

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

1.5 知识要点

Spring容器加载properties文件

<context:property-placeholder location="xx.properties"/>
<property name="" value="${key}"/>

2. Spring注解开发

【出现问题】Duplicate class found in the file

在文件中发现重复的类

解决方法:给相同名字的类,换一个名字。

配置

结果如下:

通过注解实现配置:

2.1 Spring原始注解

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

Spring原始注解主要是替代的配置

注解

说明

@Component

使用在类上用于实例化Bean(完成对象创建)

@Controller

使用在web层类上用于实例化Bean

@Service

使用在service层类上用于实例化Bean

@Repository

使用在dao层类上用于实例化Bean

@Autowired

使用在字段上用于根据类型依赖注入(对象类型的注入)

@Qualifier

结合@Autowired一起使用用于根据名称进行依赖注入

@Resource

相当于@Autowired+@Qualifier,按照名称进行注入

@Value

注入普通属性(普通属性的注入)

@Scope

标注Bean的作用范围

@PostConstruct

使用在方法上标注该方法是Bean的初始化方法

@PreDestroy

使用在方法上标注该方法是Bean的销毁方法

注意:

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

<!--注解的组件扫描-->
<context:component-scan base-package="com.itheima"></context:component-scan>

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

//@Component("userDao")
@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Override
    public 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;
    @Override
    public void save() {       
         userDao.save();
    }
}

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

@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Value("注入普通数据")
    private String str;
    @Value("${jdbc.driver}")
    private String driver;
    @Override
    public 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标注销毁方法

@PostConstruct
public void init(){
    System.out.println("初始化方法....");
}
@PreDestroy
public void destroy(){
    System.out.println("销毁方法.....");
}

2.2 Spring新注解

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

非自定义的Bean的配置:

加载properties文件的配置:context:property-placeholder

组件扫描的配置:context:component-scan

引入其他文件:

注解

说明

@Configuration

用于指定当前类是一个 Spring 配置类,当创建容器时会从该类上加载注解

@ComponentScan

用于指定 Spring 在初始化容器时要扫描的包。 作用和在 Spring 的 xml 配置文件中的 一样

@Bean

使用在方法上,标注将该方法的返回值存储到 Spring 容器中

@PropertySource

用于加载.properties 文件中的配置

@Import

用于导入其他配置类

一开始我的代码:

 @Bean("dataSource")  //Spring会将当前方法的返回值以指定名称存储到spring容器中
public DataSource getDataSource() throws PropertyVetoException {
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
//        基本连接参数
    dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
    dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test_spring");
    dataSource.setUser("root");
    dataSource.setPassword("123321");
    return dataSource;
}

@Configuration

@ComponentScan

@Import

@Configuration
@ComponentScan("com.itheima")
@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容器

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

3. Spring整合Junit

3.1 原始Junit测试Spring的问题

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

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

第一行代码获得应用上的对象,第二行代码获得对应的要被测试的对象

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

3.2 上述问题解决思路

让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉它

将需要进行测试Bean直接在测试类中进行注入

3.3 Spring集成Junit步骤

①导入spring集成Junit的坐标

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

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

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

⑤创建测试方法进行测试

3.4 Spring集成Junit代码实现

①导入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>

②使用@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 {
    @Autowired
    private UserService userService;
}

⑤创建测试方法进行测试

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

Spring集成Junit步骤

①导入spring集成Junit的坐标

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

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

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

⑤创建测试方法进行测试

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

CSDN 周赛38期题解

CSDN 周赛38期题解1、题目名称&#xff1a;代写匿名信2、题目名称&#xff1a;寻因找祖3、题目名称&#xff1a;小Q新式棋盘4、题目名称&#xff1a;拯救公主结束语1、题目名称&#xff1a;代写匿名信 小Q想要匿名举报XX领导不务正业&#xff01; 小Q害怕别人认出他的字迹。 他…

【性能分析】分析JVM出现的内存泄漏的性能故障

分析JVM出现的内存持续增加的性能故障手册 前言 本文通过常见的性能文件为例&#xff0c;提供简单清晰的思路去快速定位问题根源&#xff0c;从而可以快速解决性能故障。 性能问题介绍 在性能测试工作中针对Java程序最重要的是要关注JVM的内存消耗情况&#xff0c;JVM的内存…

基于数据安全的沙盘推演体系

背景 2022年由IBM和Ponemon研究所联合发布的一份全球性的研究报告&#xff0c;分析了550家遭受数据泄露事件的组织的各种成本和影响因素。根据报告&#xff0c;2022年全球数据泄露规模和平均成本均创下历史新高&#xff0c;数据泄露事件的平均成本高达435万美元&#xff0c;比2…

自动标注工具 Autolabelimg

原理简介~~ 对于数据量较大的数据集&#xff0c;先对其中一部分图片打标签&#xff0c;Autolabelimg利用已标注好的图片进行训练&#xff0c;并利用训练得到的权重对其余数据进行自动标注&#xff0c;然后保存为xml文件。 一、下载yolov5v6.1 https://github.com/ultralytic…

java HashSet 源码分析(深度讲解)

目录 一、前言 二、HashSet简介 三、HashSet的底层实现 四、HashSet的源码解读&#xff08;断点调试&#xff09; 0.准备工作 : 1.向集合中添加第一个元素&#xff08;141&#xff09; : ①跳入无参构造。 ②跳入add方法。 ③跳入put方法。 ④跳入putVal方法。 ⑤跳入res…

inode和软硬链接

文章目录&#xff1a;一、理解文件系统1.1 什么是inode1.2 磁盘了解1.2.1磁盘的硬件结构1.2.2 磁盘的分区1.2.3 EXT2文件系统二、软硬链接2.1 软链接2.2 硬链接一、理解文件系统 1.1 什么是inode inodes 是文件系统中存储文件元数据的数据结构。每个文件或目录都有一个唯一的 …

用Pytorch构建一个喵咪识别模型

本文参加新星计划人工智能(Pytorch)赛道&#xff1a;https://bbs.csdn.net/topics/613989052 目录 一、前言 二、问题阐述及理论流程 2.1问题阐述 2.2猫咪图片识别原理 三、用PyTorch 实现 3.1PyTorch介绍 3.2PyTorch 构建模型的五要素 3.3PyTorch 实现的步骤 3.3.…

Linux--线程安全、多线程fork问题

目录 一、概念&#xff1a; 二、利用空格分割字符串&#xff1a; 1.代码&#xff1a; 2.结果&#xff1a; 3.解决方法&#xff1a; 三、多线程fork&#xff08;&#xff09; 1.代码&#xff1a; 2.线程id 3.增加fork&#xff08;&#xff09;代码&#xff1a; 4.改变fo…

【Matlab算法】粒子群算法求解一维线性函数问题(附MATLAB代码)

MATLAB求解一维线性函数问题前言正文函数实现可视化处理可视化结果前言 一维线性函数&#xff0c;也称为一次函数&#xff0c;是指只有一个自变量xxx的函数&#xff0c;且函数表达式可以写成yaxbyaxbyaxb的形式&#xff0c;其中aaa和bbb是常数。具体来说&#xff0c;aaa称为斜…

Spark了解

目录 1 概述 2 发展 3 Spark和Hadoop 4 Spark核心模块 1 概述 Apache Spark是一个快速、通用、可扩展的分布式计算系统&#xff0c;最初由加州大学伯克利分校的AMPLab开发。 Spark可以处理大规模数据处理任务&#xff0c;包括批处理、迭代式算法、交互式查询和流处理等。Spa…

seata服务搭建

它支持两种存储模式&#xff0c;一个是文件&#xff0c;一个是数据库&#xff0c;下面我们分别介绍一下这两种配置nacos存储配置&#xff0c;注意如果registry.conf中注册和配置使用的是file&#xff0c;就会去读取file.config的配置&#xff0c;如果是nacos则通过nacos动态读取…

图形视图框架QGraphicsScene(场景,概念)

QGraphicsScene 该类充当 QGraphicsItems 的容器。它与 QGraphicsView 一起使用&#xff0c;用于在 2D 表面上可视化图形项目&#xff0c;例如线条、矩形、文本甚至自定义项目。 QGraphicsScene具有的功能&#xff1a; 提供用管理大量数据项的高速接口传播事件到每一个图形项…

12个 Python 装饰器让代码cleaner

0 — 引言装饰器能在在不影响质量的情况下用更少的代码做更多的事情。Python 装饰器是强大的工具&#xff0c;可帮助你生成干净、可重用和可维护的代码。我等了很久才想了解这些抽象&#xff0c;现在我已经有了扎实的理解&#xff0c;本篇是为了帮助你也掌握这些对象背后的概念…

Android Lacent Aop 字节编码修复7.1系统Toast问题(WindowManager$BadTokenException)

近期在Bugly上出现7.1以下设备上出现大量BadTokenException&#xff1a; android.view.WindowManager$BadTokenExceptionUnable to add window -- token android.os.BinderProxy6c0415d is not valid; is your activity running?报错堆栈&#xff0c;如下所示&#xff1a; …

【Linux】学会这些基本指令来上手Linux吧

前言上篇文章介绍了一些常用的指令&#xff0c;这篇文章再来介绍一下Linux必须学会的指令。一.时间相关的指令ate显示date 指定格式显示时间&#xff1a; date %Y:%m:%d date 用法&#xff1a;date [OPTION]... [FORMAT]1.在显示方面&#xff0c;使用者可以设定欲显示的格式&am…

iOS 紧急通知

一般通知 关于通知的各种配置和开发&#xff0c;可以参考推送通知教程&#xff1a;入门 – Kodeco&#xff0c;具有详细步骤。 紧急通知表现 紧急通知不受免打扰模式和静音模式约束。当紧急通知到达时&#xff0c;会有短暂提示音量和抖动&#xff08;约2s&#xff09;。未锁…

nodejs篇 express(1)

文章目录前言express介绍安装RESTful接口规范express的简单使用一个最简单的服务器&#xff0c;仅仅只需要几行代码便可以实现。restful规范的五种接口类型请求信息req的获取响应信息res的设置中间件的使用自定义中间件解决跨域nodejs相关其它内容前言 express作为nodejs必学的…

RK3588平台开发系列讲解(NPU篇)NPU调试方法

平台内核版本安卓版本RK3588Linux 5.10Android 12文章目录 一、日志等级二、NPU 支持查询设置项沉淀、分享、成长,让自己和他人都能有所收获!😄 📢本篇我们一起来看一下NPU的调试方法。 一、日志等级 NPU 的运行库会根据开发板上的系统环境变量输出一些日志信息或者生成…

LeetCode--缺失的第一个正数(41)和 接雨水(42)

目录 缺失的第一个正数 接雨水 0ms&#xff0c;100% 代码 缺失的第一个正数 来源&#xff1a;力扣&#xff08;LeetCode&#xff09; 链接&#xff1a;https://leetcode.cn/problems/first-missing-positive 题目&#xff1a;给你一个未排序的整数数组 nums &#xff0c;请…

Elastic 之 elasticsearch 基本操作

一、基本概念 Elasticsearch也是基于Lucene的全文检索库&#xff0c;本质也是存储数据&#xff0c;很多概念与MySQL类似的。 对比关系&#xff1a; 索引&#xff08;indices&#xff09;----------------------Databases 数据库 类型&#xff08;type&#xff09;-----------…
最新文章