SpringBoot学习笔记(一)

本文详细介绍了Spring Boot的核心功能、快速入门、配置文件类型、属性注入、自动配置原理、起步依赖解析、Lombok应用、Spring MVC整合、事务管理、Mybatis集成、通用Mapper使用、测试支持、JPA集成以及Redis整合,旨在帮助读者全面掌握Spring Boot的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Spring Boot概述

目标:了解Spring Boot是什么,有什么作用

小结

  Spring Boot是一个便捷搭建 基于spring工程的脚手架;作用是帮助开发人员快速搭建大型的spring 项目。尽可能的减少一切xml配置,做到拆箱即用,简化工程的配置,依赖管理;实现开发人员把时间都集中在业务开发上。
在这里插入图片描述

1.1springboot特点

Spring Boot 主要特点是:

  创建独立的Spring应用,为所有 Spring 的开发者提供一个非常快速的、广泛接受的入门体验
直接嵌入应用服务器,如tomcat、jetty、undertow等;不需要去部署war包

  提供固定的启动器依赖去简化组件配置;实现开箱即用(启动器starter-其实就是Spring Boot提供的一个jar包),通过自己设置参数(.properties或.yml的配置文件),即可快速使用。
自动地配置Spring和其它有需要的第三方依赖

  提供了一些大型项目中常见的非功能性特性,如内嵌服务器、安全、指标,健康检测、外部化配置等

  绝对没有代码生成,也无需 XML 配置。

1.2 springboot的核心功能

·起步依赖

  起步依赖本质上是一个Maven项目对象模型(Project Object Model,POM),定义了对其他库的传递依赖,这些东西加在一起即支持某项功能。
简单的说,起步依赖就是将具备某种功能的坐标打包到一起,并提供一些默认的功能。
·自动配置

  Spring Boot的自动配置是一个运行时(更准确地说,是应用程序启动时)的过程,考虑了众多因素,才决定Spring配置应该用哪个,不该用哪个。该过程是Spring自动完成的。

2. Spring Boot快速入门

目标:能够使用Spring Boot搭建项目

分析

需求:可以在浏览器中访问http://localhost:8080/hello输出一串字符

实现步骤:

  1. 创建maven工程;
  2. 添加依赖(启动器依赖,spring-boot-starter-web);
    添加父工程坐标
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.5.RELEASE</version>
</parent>

添加web启动器

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
</dependencies>
  1. 创建启动类;
@SpringBootApplication//这个配置告诉springboot这个类是工程的启动的入口
public class MySpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class);
    }
}

  1. 创建处理器Controller;
@Controller
public class QuickController {

    @RequestMapping("/quick")
    @ResponseBody//如果想要页面返回字符串就必须添加responseBody,
    // 不加则会去找对应网页名字的网页
    public String quick(){
        return "hello SpringBoot";
    }
}
  1. 测试
    在这里插入图片描述springboot热部署的配置
    导入依赖坐标
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

在idea中设置自动编译:
在这里插入图片描述

首先ctrl+alt+s打开设置(Other Settings 的设置是对整个工作空间项目都启作用,而Settings…的设置是对整个项目启作用),搜索Compliler,勾选Build project automatically,如下图所示:
在这里插入图片描述

.按住ctrl + shift + alt + /,出现如下图所示界面,点击Registry…,如下图:
在这里插入图片描述

点击进入后,勾选compiler.automake.allow.when.app.running后关闭即可

通过以上步骤,就完成了SpringBoot项目的热部署功能!!!

快速创建springboot项目方式二

在这里插入图片描述在依赖中选择自己需要的依赖,springboot会自动帮助我们添加好我们所需要的依赖坐标
在这里插入图片描述在这里插入图片描述

小结

Spring Boot工程可以通过添加启动器依赖和创建启动引导类实现快速创建web工程。

spring-boot-starter-web默认的应用服务器端口是8080

3.SpringBoot配置文件类型

3 .1.1SpringBoot配置文件类型和作用

  SpringBoot是基于约定的,所以很多配置都有默认值,但如果想使用自己的配置替换默认配置的话,就可以使用applidation.properties或者application.yml (applicationlyaml)进行配置。
SpringBoot默认会从Resources目录下加载application.properties或application.yml(application.yaml)文件

  其中,application.properties文件是键值对类型的文件,之前一直在使用,所以此处不在对properties文件的格式进行阐述。除了properties文件外,SpringBoot还可以使用yml文件进行配置,下面对yml文件进行讲解。

3.1.2 application.yml配置文件
3.1.2.1 yml配置文件简介

  YML文件格式是YAML(YAML Aint Markup Language)编写的文件格式,YAML是一种直观的能够被电脑识别的的数据数据序列化格式,并且容易被人类阅读,容易和脚本语言交互的,可以被支持YAML库的不同的编程语言程序导入,比如:CIC++,Ruby,Python,Java,Perl,C#,PHP等。YML文件是以数据为核心的,比传统的xml方式更加简洁。

  YML文件的扩展名可以使用.yml或者.yaml

3.1.2.2 yml配置文件语法:

      key: value; (value前有一个空格)
配置普数据代码:

name: xiaoxu

配置对象数据:

#对象数据的配置
person:
  name: sd
  age: 12
  sex: nan

#行内对象配置
person1: {name: sd,age: 22,add: beijing}

配置数据、集合(普通字符串)

 #配置数据、集合(普通字符串)
city:
  - beijing
  - shanghai
  - chengdu
  - wuhan
  - zhengzhou
  - nanyang
  - xixia
  - dongjing

#map集合的配置
map:
  key1: v1
  key2: v2
  key3: v3

4. 配置文件与配置属性映射方式

目标:可以使用@Value获取配置文件配置项并结合@Bean注册组件到Spring

分析

需求:使用Java代码配置数据库连接池,并可以在处理器中注入并使用

步骤:

  1. 添加依赖;
  2. 创建数据库;
  3. 创建数据库连接参数的配置文件jdbc.properties;
  4. 创建配置类;
  5. 改造处理器类注入数据源并使用

小结

package com.zy.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {

    @Value("${jdbc.url}")
    String url;
    @Value("${jdbc.driverClassName}")
    String driverClassName;
    @Value("${jdbc.username}")
    String username;
    @Value("${jdbc.password}")
    String password;

    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

}

4. Spring Boot属性注入方式

目标:能够使用@ConfigurationProperties实现Spring Boot配置文件配置项读取和应用

分析

需求:将配置文件中的配置项读取到一个对象中;

实现:可以使用Spring Boot提供的注解@ConfigurationProperties,该注解可以将Spring Boot的配置文件(默认必须为application.properties或application.yml)中的配置项读取到一个对象中。

实现步骤:

  1. 创建配置项类JdbcProperties类,在该类名上面添加@ConfigurationProperties;
  2. 将jdbc.properties修改名称为application.properties;
  3. 将JdbcProperties对象注入到JdbcConfig;
  4. 测试

小结

  • 使用@ConfigurationProperties编写配置项类将配置文件中的配置项设置到对象中
@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {

    private String url;
    private String driverClassName;
    private String username;
    private String password;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

  • 使用@ConfigurationProperties在方法上面使用
    @Bean
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource() {
        return new DruidDataSource();
    }

5. 多个yml文件配置

目标:可以将多个yml文件在application.yml文件中配置激活

分析

yaml与properties配置文件除了展示形式不相同以外,其它功能和作用都是一样的;在项目中原路的读取方式不需要改变。

1)yml配置文件的特征:

  1. 树状层级结构展示配置项;
  2. 配置项之间如果有关系的话需要分行空两格;
  3. 配置项如果有值的话,那么需要在 :之后空一格再写配置项值;

将application.properties配置文件修改为application.yml的话:

jdbc:
  driverClassName: com.mysql.jdbc.Driver
  url: jdbc:mysql://127.0.0.1:3306/heima
  username: root
  password: root

key:
  abc: cba
  def:
    - g
    - h
    - j

2)多个yml配置文件;在spring boot中是被允许的。这些配置文件的名称必须为application-***.yml,并且这些配置文件必须要在application.yml配置文件中激活之后才可以使用。

3)如果properties和yml配置文件同时存在在spring boot项目中;那么这两类配置文件都有效。在两个配置文件中如果存在同名的配置项的话会以properties文件的为主。

小结

在多个配置文件时,需要将这些文件在application.yml文件中进行激活:

#激活配置文件;需要指定其它的配置文件名称
spring:
  profiles:
    active: abc,def

6. 自动配置原理

目标:了解Spring Boot项目的配置加载流程

  使用Spring Boot之后,一个整合了SpringMVC的WEB工程开发,变的无比简单,那些繁杂的配置都消失不见了,这
是如何做到的?
一切魔力的开始,都是从我们的main函数来的,所以我们再次来看下启动类:

@SpringBootApplication
public class Application{
	public static void main(String[] args){
	SpringApplication.run(Application.class,args);
	} 
}

我们发现特别的地方有两个:

  • 注解:@SpringBootApplication
  • run方法:SpringApplication.run()
    我们分别来研究这两个部分。

6.1@SpringBootApplication的分析

首先点进去注解SpringBootApplication中查看源码
在这里插入图片描述这里重点的注解有3个:

  • @SpringBootConfiguration
  • @EnableAutoConfiguration
  • @ComponentScan
6.1.1@SpringBootConfiguration

表示它是一个配置类
继续查看源码:
在这里插入图片描述
  通过这段我们可以看出,在这个注解上面,又有一个 @Configuration 注解。通过上面的注释阅读我们知道:这个注解的作用就是声明当前类是一个配置类,然后Spring会自动扫描到添加了 @Configuration 的类,并且读取其中的配置信息。而 @SpringBootConfiguration 是来声明当前类是SpringBoot应用的配置类,项目中只能有一个。所以一般我们无需自己添加。

6.1.1@EnableAutoConfiguration

在这里插入图片描述@EnableAutoConfiguration如何实现判断是否自动配置功能;通过源码可以看出它引入了AutoConfigurationImpotSelector这个类;查看源码:
首先看selectImports的实现

public class AutoConfigurationImportSelector{
public String[] selectImports(AnnotationMetadata annotationMetadata) {
        if (!this.isEnabled(annotationMetadata)) {
            return NO_IMPORTS;
        } else {
            AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
            AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
            return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
        }
    }
}

然后点进去getAutoConfigurationEntry()方法:

protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,
			AnnotationMetadata annotationMetadata) {
		if (!isEnabled(annotationMetadata)) {
			return EMPTY_ENTRY;
		}
		AnnotationAttributes attributes = getAttributes(annotationMetadata);
		List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
		configurations = removeDuplicates(configurations);
		Set<String> exclusions = getExclusions(annotationMetadata, attributes);
		checkExcludedClasses(configurations, exclusions);
		configurations.removeAll(exclusions);
		configurations = filter(configurations, autoConfigurationMetadata);
		fireAutoConfigurationImportEvents(configurations, exclusions);
		return new AutoConfigurationEntry(configurations, exclusions);
	}

再次点入getCandidateConfigurations()方法:

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
		List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
				getBeanClassLoader());
		Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
				+ "are using a custom packaging, make sure that file is correct.");
		return configurations;
	}

到这里你会发现有这么句话No auto configuration classes found in META-INF/spring.factories,
在这里插入图片描述

6.1.3 默认配置类

我们打开刚才的spring.factories文件:
在这里插入图片描述可以发现以EnableAutoConfiguration接口为key的一系列配置,key所对应的值,就是所有的自动配置类,可以在当
前的jar包中找到这些自动配置类:
在这里插入图片描述

是否支持自动配置扫描
官网的说明:
在这里插入图片描述翻译为:

第二级的注解 @EnableAutoConfiguration ,告诉Spring Boot基于你所添加的依赖,去“猜测”你想要如何配
置Spring。比如我们引入了 spring-boot-starter-web ,而这个启动器中帮我们添加了 tomcat 、 SpringMVC
的依赖。此时自动配置就知道你是要开发一个web应用,所以就帮你完成了web及SpringMVC的默认配置了!

  总结,Spring Boot内部对大量的第三方库或Spring内部库进行了默认配置,这些配置是否生效,取决于我们是否引入了对应库所需的依赖,如果有那么默认配置就会生效。

  所以,我们使用SpringBoot构建一个项目,只需要引入所需框架的依赖,配置就可以交给SpringBoot处理了。除非你不希望使用SpringBoot的默认配置,它也提供了自定义配置的入口。

6.1.3@ComponScan

组件扫描
跟进源码:
在这里插入图片描述并没有看到什么特殊的地方。我们查看注释:

在这里插入图片描述大概翻译:

配置组件扫描的指令。提供了类似与 context:component-scan 标签的作用
通过basePackageClasses或者basePackages属性来指定要扫描的包。如果没有指定这些属性,那么将从声明
这个注解的类所在的包开始,扫描包及子包

  而我们的@SpringBootApplication注解声明的类就是main函数所在的启动类,因此扫描的包是该类所在包及其子包。因此,一般启动类会放在一个比较前的包目录中。

小结
SpringBoot为我们提供了默认配置,而默认配置生效的步骤:

  @EnableAutoConfiguration注解会去寻找META_INF/spring.factories文件,读取其中以EnableAutoconfiguration为key的所有类的名称,这些类就是提前写好的自动配置类。

  这些类都声明了@configuration注解,并且通过@Bean注解提前配置了我们所需要的一切实例

  但是,这些配置不一定生效,因为有Cconditiona1on注解,满足一定条件才会生效。比如条件之一:是一些相关的类要存在
类要存在,我们只需要引入了相关依赖(启动器),依赖有了条件成立自动配置生效。
  如果我们自己配置了相关Bean,那么会覆盖默认的自动配置的Bean
  我们还可以通过配置application.yml文件,来覆盖自动配置中的属性

1)启动器

  所以,我们如果不想配置,只需要引入依赖即可,而依赖版本我们也不用操心,因为只要引入了SpringBoot提供的
stater(启动器),就会自动管理依赖及版本了。
因此,玩SpringBoot的第一件事情,就是找启动器,SpringBoot提供了大量的默认启动器
2)全局配置

  另外,SpringBoot的默认配置,都会读取默认属性,而这些属性可以通过自定义 application.properties 文件来进行覆盖。这样虽然使用的还是默认配置,但是配置中的值改成了我们自定义的。
  因此,玩SpringBoot的第二件事情,就是通过 application.properties 来覆盖默认属性值,形成自定义配置。我们需要知道SpringBoot的默认属性key,非常多,可以再idea中自动提示
属性文件支持两种格式,application.properties和application.yml

7.SpringBoot起步依赖的原理分析

7.1.1分析spring-boot-starter-parent

按住Ctrl点击pom.xml中的spring-boot-starter-parent,跳转到了spring-boot-starter-parent的porm.xml的配置文件

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

在这里插入图片描述在这里插入图片描述点进去spring-boot-dependencies后
在这里插入图片描述
  总结:导入spring-boot-parent父坐标,为我们规定好了我们可能需要用到的技术的版本,避免了版本冲突问题

7.1.2对依赖spring-boot-web-starter的分析

 <dependencies>
<!--        web工程起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

按住Ctrl键点进去spring-boot-starter-web后
在这里插入图片描述在这里插入图片描述以上,便完成了依赖打包和版本控制问题

7. lombok应用

目标:使用lombok的注解实现pojo类的简化

分析

使用Spring Boot整合SSM工程;需要使用到数据库数据。

  • 将数据库表数据导入到数据库中(springboot_test);

  • 编写数据库表对应的实体类;一般情况下需要编写get/set/toString等这些方法会耗时并且会让实体类看起来比较臃肿。可以使用lombok插件对实体类进行简化。

    lombok是一个插件工具类包;提供了一些注解@Data、@Getter等这些注解去简化实体类中的构造方法、get/set等方法的编写。

    1. 在IDEA中安装lombok插件;
      在这里插入图片描述

    2. 添加lombok对应的依赖到项目pom.xml文件;

    3. 改造实体类使用lombok注解

小结

在Bean上使用:
@Data :自动提供getter和setter、hashCode、equals、toString等方法
@Getter:自动提供getter方法
@Setter:自动提供setter方法
@Slf4j:自动在bean中提供log变量,其实用的是slf4j的日志功能。

8. Spring Boot整合-SpringMVC端口和静态资源

目标:可以修改tomcat的端口和访问项目中的静态资源

分析

  • 修改tomcat端口

    查询**Properties,设置配置项(前缀+类变量名)到application配置文件中

  • 访问项目中的静态资源

    静态资源放置的位置;放置静态资源并访问这些资源

小结

  • 修改项目tomcat端口:
#tomcat端口
server:
  port: 80
  • 在spring boot项目中静态资源可以放置在如下目录:

9.Spring Boot整合-SpringMVC拦截器

目标:可以在Spring Boot项目中配置自定义SpringMVC拦截器

分析

  1. 编写拦截器(实现HandlerInterceptor);
  2. 编写配置类实现 WebMvcConfigurer,在该类中添加各种组件;
  3. 测试

小结

可以在spring boot项目中通过配置类添加各种组件;如果要添加拦截器的话:

package com.itheima.config;

import com.itheima.interceptor.MyInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    //注册拦截器
    @Bean
    public MyInterceptor myInterceptor(){
        return new MyInterceptor();
    }

    //添加拦截器到spring mvc拦截器链
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor()).addPathPatterns("/*");
    }
}

11. Spring Boot整合-事务和连接池

目标:配置Spring Boot自带默认的hikari数据库连接池和使用@Transactional注解进行事务配置

分析

  • 事务配置

    1. 添加事务相关的启动器依赖,mysql相关依赖;
    2. 编写业务类UserService使用事务注解@Transactional
  • 数据库连接池hikari配置

    只需要在application配置文件中指定数据库相关参数

小结

  • 事务配置;只需要添加jdbc启动器依赖
  • 数据库连接池使用默认的hikari,在配置文件中配置如下:
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/springboot_test
    username: root
    password: root

12. Spring Boot整合-Mybatis

目标:配置Mybatis在Spring Boot工程中的整合包,设置mybatis的实体类别名,输出执行sql语句配置项

分析

  1. 添加启动器依赖;
 <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
  1. 配置Mybatis:实体类别名包,日志,映射文件等;
    application.properties:
#数据库连接信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=1234

#配置mybatis的相关
#pojo别名扫描包
mybatis.type-aliases-package=com.zy.domain
#加载mybatis映射文件
mybatis.mapper-locations=classpath:mapper/*Mapper.xml

junit测试

//springboot整合junit和spring整合junit稍有区别
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootMybatisApplication.class)
public class MyTest {

    @Autowired
    UserMapper userMapper;

    @Test
    public void test(){

        List<User> users = userMapper.queryUserList();
        System.out.println(users);
      //  users.forEach(System.out::println);

    }
}

结果:
在这里插入图片描述

小结

  • 添加mybatis官方对于spring boot的一个启动器

            <!--mybatis -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.0.1</version>
            </dependency>
    
    
    
  • 配置mybatis

    mybatis:
      # 实体类别名包路径
      type-aliases-package: com.zy.pojo
      # 映射文件路径
      # mapper-locations: classpath:mappers/*.xml
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
    
  • 设置启动器类中的mapper扫描

13. Spring Boot整合-通用Mapper

目标:配置通用Mapper组件到Spring Boot项目中并使用Mapper接口

分析

通用Mapper:可以实现自动拼接sql语句;所有的mapper都不需要编写任何方法也就是不用编写sql语句。可以提高开发效率。

  1. 添加启动器依赖;
  2. 改造UserMapper继承Mapper;
  3. 修改启动引导类Application中的Mapper扫描注解;
  4. 修改User实体类添加jpa注解;
  5. 改造UserService实现业务功能;

小结

在启动引导类上面的mapper扫描注解 一定要修改为 通用mapper的扫描注解

14. Spring Boot整合测试

目标:可以访问处理器对应路径将数据库中的数据根据id查询

分析

  1. 改造HelloController,注入UserService利用其方法实现查询;
  2. 启动项目进行测试 http://localhost/user/用户id --> http://localhost/user/8

小结

修改了HelloController:

    @Autowired
    private UserService userService;

    /**
     * 根据用户id查询用户
     * @param id 用户id
     * @return 用户
     */
    @GetMapping("/user/{id}")
    public User queryById(@PathVariable Long id){
        return userService.queryById(id);
    }


15. Spring Boot整合-Junit

目标:在Spring Boot项目中使用Junit进行单元测试UserService的方法

分析

  1. 添加启动器依赖spring-boot-starter-test;
  2. 编写测试类

小结

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @Test
    public void queryById() {
        User user = userService.queryById(8L);
        System.out.println("user = " + user);
    }

    @Test
    public void saveUser() {
        User user = new User();
        user.setUserName("test2");
        user.setName("test2");
        user.setAge(13);
        user.setPassword("123456");
        user.setSex(1);
        user.setCreated(new Date());
        userService.saveUser(user);
    }
}

在Spring Boot项目中如果编写测试类则必须要在类上面添加@SpringBootTest

16.SpringBoot集成Spring Data JPA

添加起步依赖:

<!--            springboot-jpa的起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        

添加数据库驱动依赖:

<!--        数据库连接的依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

在application.properties中配置数据库和jpa的相关属性

#JPA Configuration
spring.jpa.database=MYSQL
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update

编写实体类

@Entity//表示该类为实体类
@Table()
public class User  implements Serializable
{
   @Id//该注解表示该属性为主键id
    @GeneratedValue(strategy =  GenerationType.IDENTITY)//主键自增策略
    private int uid;
    private String username;
    private String password;
    private long birthday;
    }

编写接口

public interface UserRepository  extends JpaRepository<User,Integer> {

    public List<User> queryAllUser();
}

编写测试类;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootJpaApplication.class)
public class JPATest {

    @Autowired
    private UserRepository userRepository;
    @Test
    public void test(){
        List<User> users = userService.findAllUser();
        System.out.println(users);
    }

16. Spring Boot整合-redis

目标:在Spring Boot项目中使用Junit测试RedisTemplate的使用

分析

  1. 添加启动器依赖;spring-boot-starter-data-redis
  2. 配置application.yml中修改redis的连接参数;(redis需要启动)
  3. 编写测试类应用RedisTemplate操作redis中的5种数据类型(string/hash/list/set/sorted set)

小结

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void test(){
        //string 字符串
        //redisTemplate.opsForValue().set("str", "heima");
        redisTemplate.boundValueOps("str").set("heima");
        System.out.println("str = " + redisTemplate.opsForValue().get("str"));

        //hash 散列
        redisTemplate.boundHashOps("h_key").put("name", "heima");
        redisTemplate.boundHashOps("h_key").put("age", 13);
        //获取所有域
        Set set = redisTemplate.boundHashOps("h_key").keys();
        System.out.println(" hash散列的所有域:" + set);
        //获取所有值
        List list = redisTemplate.boundHashOps("h_key").values();
        System.out.println(" hash散列的所有域的值:" + list);

        //list 列表
        redisTemplate.boundListOps("l_key").leftPush("c");
        redisTemplate.boundListOps("l_key").leftPush("b");
        redisTemplate.boundListOps("l_key").leftPush("a");
        //获取全部元素
        list = redisTemplate.boundListOps("l_key").range(0, -1);
        System.out.println(" list列表中的所有元素:" + list);

        // set 集合
        redisTemplate.boundSetOps("s_key").add("a", "b", "c");
        set = redisTemplate.boundSetOps("s_key").members();
        System.out.println(" set集合中的所有元素:" + set);

        // sorted set 有序集合
        redisTemplate.boundZSetOps("z_key").add("a", 30);
        redisTemplate.boundZSetOps("z_key").add("b", 20);
        redisTemplate.boundZSetOps("z_key").add("c", 10);
        set = redisTemplate.boundZSetOps("z_key").range(0, -1);
        System.out.println(" zset有序集合中的所有元素:" + set);
    }
}


17. Spring Boot项目部署

目标:将Spring Boot项目使用maven指令打成jar包并运行测试

分析

  1. 需要添加打包组件将项目中的资源、配置、依赖包打到一个jar包中;可以使用maven的package
  2. 部署:java -jar 包名

小结

  • 添加打包组件

        <build>
            <plugins>
               <!-- 打jar包时如果不配置该插件,打出来的jar包没有清单文件 -->
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    
  • 部署运行

    java -jar 包名
    
    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值