Day73--Springboot


title: Day73–Springboot
date: 2021-05-19 13:50:02
author: Liu_zimo


SpringBoot是所有基于Spring开发的项目的起点。SpringBoot其实不是什么新的框架,它默认配置了很多框架的使用方式,就像maven整合了所有的jar包,spring boot整合了很多的技术,提供了JavaEE的大整合。

spring 官方的网站:https://spring.io/

Spring Boot概述

一般把Spring Boot称为搭建程序的脚手架或者说是便捷搭建基于Spring的工程脚手架。其最主要作用就是帮助开发人员快速的构建庞大的spring项目,并且尽可能的减少一切xml配置,做到开箱即用,迅速上手,让开发人员关注业务而非配置。

  • 为什么要学习spring boot

    java一直被人诟病的一点就是臃肿、麻烦。当我们还在辛苦的搭建项目时,可能Python程序员已经把功能写好了,究其原因注意是两点:

    • 复杂的配置

      项目各种配置其实是开发时的损耗,因为在思考Spring特性配置和解决业务问题之间需要进行思维切换,所以写配置挤占了写应用程序逻辑的时间。

    • 一个是混乱的依赖管理

      项目的依赖管理也是吃力不讨好的事情。决定项目里要用哪些库就已经够让人头痛的了,你还要知道这些库的哪个版本和其他库不会有冲突,这难题实在太棘手。并且,依赖管理也是一种损耗,添加依赖不是写应用程序代码。一旦选错了依赖的版本,随之而来的不兼容问题毫无疑问会是生产力杀手。

  • Spring Boot简化了基于Spring的应用开发,只需要"run"就能创建一个独立的、生产级别的Spring应用;
    Spring Boot为Spring平台及第三方库提供开箱即用的设置(提供默认设置,存放默认配置的包就是启动器starter),这样我们就可以简单的开始;
    多数Spring Boot应用只需要很少的Spring配置;

我们可以使用Spring Boot创建java应用,并使用java -jar启动它,就能得到一个生产级别的web工程

  • Spring Boot主要特点是:
    • 创建独立的Spring应用,为所有Spring的开发者提供一个非常快速的、广泛接受的入门体验
    • 直接嵌入应用服务器,如tomcat、jetty、undertow等;不需要去部署war包
    • 提供固定的启动器依赖去简化组件配置;实现开箱即用(启动器starter-其实就是Spring Boot提供的一个jar包),通过自己设置参数(.properties或.yml的配置文件),即可快速使用
    • 自动地配置Spring和其它有需要的第三方依赖
    • 提供了一些大型项目中常见的非功能性特性,如内嵌服务器、安全、指标,健康检测、外部化配置等
    • 绝对没有代码生成,也无需XML配置

Spring Boot入门

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

  • 实现步骤:

    1. 创建工程,引入父类依赖,指定spring boot 版本
    2. 添加依赖(启动器依赖,spring-boot-starter-web)
    3. 创建启动类
    4. 创建处理器Controller
    5. 测试
  • 添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!--添加父类-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
    </parent>
    <groupId>com.zimo</groupId>
    <artifactId>springboot</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--指定Java版本-->
    <properties>
        <java.version>1.8</java.version>
    </properties>
	<!--添加启动器依赖-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>
  • 启动引导类
package com.zimo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * spring boot 启动类
 *      spring boot都有一个启动引导类,这是工程入口
 * @author Liu_zimo
 * @version v0.1 by 2021/5/28 16:56
 */
// 在引导类上添加SpringBootApplication注解
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  • 处理器Controller
package com.zimo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 处理器
 *
 * @author Liu_zimo
 * @version v0.1 by 2021/5/28 16:59
 */
@RestController // 组合注解ResponseBody + Controller
public class HelloController {

    @GetMapping("hello")
    public String hello(){
        return "Hello Spring Boot";
    }
}
  • spring-boot-starter-web:默认的应用服务器端口是8080

应用Spring Boot Yaml配置文件

如果需要配置一个Bean,比如配置一个数据库连接池,以前配置xml方式如下:

<!--配置连接池-->
<bean id="dataSource" class="com.alibaba.druid.poo1.DruidDataSource" init-method="init" destroy-method="close">
    <property name="url" value="${jdbc.ur1}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

Spring配置历史

  1. Spring1.0时代:jdk1.5刚出,注解未盛行,所有bean使用xml配置
  2. Spring2.0时代:注解不完善,xml + 注解,混合使用
  3. Spring3.0时代:注解完善,spring boot替代xml

Java配置

  • java配置主要靠java类和一些注解,比较常用的注解有:

    • @Configuration:声明一个类作为配置类,替代xml文件
    • @Bean:声明在方法上,将方法的返回值加入Bean容器,代替<Bean>标签
    • @Value:属性注入
    • @PropertySource:指定外部属性文件
  • 需求:使用Java代码配置数据库连接池,并可以在处理器中注入并使用

  • 实现步骤:

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

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=123456
  • JdbcConfig配置类
package com.zimo.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;
/**
 * JDBC配置类
 *
 * @author Liu_zimo
 * @version v0.1 by 2021/5/31 10:27
 */
@Configuration  // 标注配置类
@PropertySource("classpath:jdbc.properties")    // 指定配置路径
public class JdbcConfig {

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

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

Spring Boot属性注入方式

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

  • 实现:可以使用spring boot提供注解@ConfigurationProperties,该注解可以将spring boot的配置文件(application.properties/application.yml)中的配置项读取到一个对象中

  • 实现步骤:

    1. 创建配置项类JdbcProperties类,在该类名上添加@ConfigurationProperties

      • 如果提示Spring Boot Configuration Annotation Processor not found in classpath时,在pom.xml中添加依赖
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-configuration-processor</artifactId>
          <!--不传递依赖-->
          <optional>true</optional>
      </dependency>
      
    2. 将jdbc.properties修改名称为application.properties

    3. 将JdbcProperties对象注入到JdbcConfig

    4. 测试

  • 优势

    • Relaxed binding:松散绑定
      • 不严格要求属性文件中的属性名与成员变量名一致。支持驼峰,中划线,下划线等等转换,甚至支持对象引导。比如:user.friend.name:代表的是user对象中的friend属性中的name属性,显然friend也是对象。@value注解就难以完成这样的注入方式。
      • meta-data support:元数据支持,帮助IDE生成属性提示(写开源框架会用到)
  • 配置项类JdbcProperties类

package com.zimo.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
 * jdbc配置项
 *
 * @author Liu_zimo
 * @version v0.1 by 2021/5/31 14:10
 */
// 从配置文件application配置中读取配置项,前缀后配置项名称要保持 松散绑定(相同)
@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
    String driverClassName;
    String url;
    String username;
    String password;
    public String getDriverClassName() { return driverClassName; }
    public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; }
    public String getUrl() { return url; }
    public void setUrl(String url) { this.url = url; }
    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; }
}
  • JdbcConfig对象
package com.zimo.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;

/**
 * JDBC对象类
 *
 * @author Liu_zimo
 * @version v0.1 by 2021/5/31 10:27
 */
@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig 
    @Bean
    public DataSource dataSource(JdbcProperties jdbcProperties){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
        dataSource.setUrl(jdbcProperties.getUrl());
        dataSource.setUsername(jdbcProperties.getUsername());
        dataSource.setPassword(jdbcProperties.getPassword());
        return dataSource;
    }
}
更优雅的注入

事实上,如果一段属性只有一个Bean需要使用,我们无需将其注入到一个类(JdbcProperties,将该类上的所有注解去掉)中。而是直接在需要的地方声明即可;再次修改dbcconfig类为如下代码:

package com.zimo.config;
// 无需此注解
//@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {...}
package com.zimo.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;

/**
 * @author Liu_zimo
 * @version v0.1 by 2021/5/31 14:27
 */
@Configuration
//@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {
    @Bean
    //声明要注入的属性前缀,Spring Boot会自动把相关属性通过set方法注入到DataSource中
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource(){
        return new DruidDataSource();
    }
}

我们直接把@configurationProperties(prefix = “jdbc”)声明在需要使用的@Bean的方法上,然后SpringBoot就会自动调用这个Bean(此处是DataSource)的set方法,然后完成注入。使用的前提是:该类必须有对应属性的set方法!

Yaml配置文件

配置文件除了可以使用application.properties类型,还可以使用后缀名为:.yml或者.yaml的类型,也就是:application.yml或者application.yaml。

正如YAML所表示的YAML Ain’t Markup Language,YAML是一种简洁的非标记语言。YAML以数据为中心,使用空白,缩进,分行组织数据,从而使得表示更加简洁易读。

  • yml配置文件的特征:
    1. 树状层级结构展示配置项;
    2. 配置项之间如果有关系的话需要分行空两个;
    3. 配置项如果有值的话,那么需要在:之后空一格再写配置项值;
  • 多个yml配置文件;在spring boot中是被允许的,这些配置文件的名称必须是application-***.yml,并且这些配置文件必须在application.yml配置文件中激活后才可以使用
  • 如果properties和yml配置文件同时存在spring boot项目中,那么这两类配置文件都有效。在两个配置文件中如果存在同名的配置项的话会以properties文件为主

基本格式:

jdbc:
	driverClassName: com.mysql.jdbc.Driver
	url: jdbc:mysql://localhost:3306/test
	username: root
	password: 123456

激活其他配置文件

# 激活文件application-abc.yml和application-def.yml
spring:
	profiles:
		active: abc,def

了解Spring Boot自动配置原理

  • @SpringBootApplication:它是一个组合注解@SpringBootConfiguration(配置注解) + @EnableAutoConfiguration + @ComponentScan(组件扫描)
  • SpringApplication.run()
  • META-INF\spring.fatories文件中定义了很多自动配置类;可以根据在pom.xml文件中添加的启动器依赖自动配置组件
  • 通过如下流程可以去修改application配置文件,改变自动配置的组件默认参数

流程:

  • spring boot 整合xx框架 → 找到对应的jar包 → 找到xx框架所在的package → xxProperties类 → 返回修改resources下的application.properties设置xx框架配置项

lombok应用

  • 使用Lombok的注解实现pojo类的简化
  • 分析:使用Spring Boot整合SSM工程;需要使用到数据库数据。
    • 将数据库表数据导入到数据库中
    • 编写数据库表对应的实体类;一般情况下需要编写get/set/toString等这些方法会耗时并且会让实体类看起来比较臃肿。可以使用lombok插件对实体类进行简化。
  • lombok是一个插件工具类包;提供了一些注解@Data、@Getter等这些注解去简化实体类中的构造方法、get/set等方法的编写
    1. 在IDEA中安装Lombok插件
    2. 添加Lombok对应的依赖添加到项目pom.xml文件
    3. 改造实体类使用Lombok注解
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
  • @Data:自动提供getter和setter、hashCode、equals、toString等方法
  • @Getter:自动提供getter方法
  • @Setter:自动提供setter方法
  • @Slf4j:自动在bean中提供log变量,其实用的是slf4j的日志功能
package com.zimo.pojo;
import lombok.Data;

import java.util.Date;

/**
 * lombok应用
 *
 * @author Liu_zimo
 * @version v0.1 by 2021/5/31 15:51
 */
// 在编译阶段会根据注解自动生成对应的方法; data包含get/set/hashCode/equals/toString等方法
@Data
public class User {
    private int id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
}

使用Spring Boot整合SpringMVC

  • 需求:可以修改tomcat的端口和访问项目中的静态资源
  • 分析:
    • 修改tomcat端口:
      • 查询xxProperties,设置配置项(前缀 + 类变量名)到application配置文件中
    • 访问项目中的静态资源:
      • 静态资源放置的位置;放置静态资源并访问这些资源
      • "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"
server:
  port: 8081

Spring Boot整合SpringMVC拦截器

  • 需求:可以在Spring Boot项目中配合自定义SpringMVC拦截器
  • 分析:
    1. 编写拦截器(实现HandlerInterceptor)
    2. 编写配置类实现WebMvcConfigurer,在该类中添加各种组件
    3. 测试

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

  • 自定义拦截器
package com.zimo.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 自定义拦截器
 *
 * @author Liu_zimo
 * @version v0.1 by 2021/5/31 18:16
 */
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("preHandle");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.debug("postHandle");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.debug("afterCompletion");
    }
}
  • 配置实现类
package com.zimo.config;
import com.zimo.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;
/**
 * @author Liu_zimo
 * @version v0.1 by 2021/6/1 10:35
 */
@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("/*");
    }
}

使用Spring Boot整合事务和连接池

  • 目标:配置Spring Boot自带默认的hikari数据库连接池和使用@Transactional注解进行事务配置
  • 分析:
    • 事务配置
      1. 添加事务相关的启动器依赖,mysql相关依赖
      2. 编写业务类UserService使用事务注解@Transactional
    • 数据库连接池hikari配置
      • 只需要在application配置文件中指定数据库相关参数

整合jdbc和事务

  • spring中的jdbc连接和事务是配置中的重要一环,在SpringBoot中该如何处理呢?

    • 答案是不需要处理,我们只要找到SpringBoot提供的启动器即可,在pom.xml文件中添加如下依赖
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    
    • 当然,不要忘了数据库驱动,SpringBoot并不知道我们用的什么数据库,这里我们选择MySQL;同样的在pom.xml文件中添加如下依赖
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
    </dependency>
    
  • hikari参数配置

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456
  • 业务类实现
package com.zimo.service;
import com.zimo.pojo.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * 业务类
 *
 * @author Liu_zimo
 * @version v0.1 by 2021/6/1 11:18
 */
@Service
public class UserService {
    // 根据id查询
    public User queryById(int id){
        ......
        return new User();
    }

    // 新增保存用户
    @Transactional  // 添加事务注解
    public void save(User user){
        ......
        System.out.println("insert user");
    }
}

使用Spring Boot整合Mybaits

  • 目标:配置Mybatis在Spring Boot工程中的整合包,设置mybatis的实体类别名,输出执行sql语句配置项
  • 分析:
    1. 添加台动器依赖
    2. 配置Mybatis:实体类别名包,日志,映射文件
    3. 配置MapperScan

mybatis

  1. SpringBoot官方并没有提供Mybatis的启动器,不过Mybatis官网自己实现了。在项目的pom.xml文件中加入如下依赖:
<!--spring boot mybaits-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
  1. 配置application.yml,常用配置如下:
# mybaits整合
mybatis:
  # 实体类别名包路径
  type-aliases-package: com.zimo.pojo
  # 映射文件路径
  #mapper-locations: classpath:maooers/*.xml
  # 日志配置
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  1. 启动类中配置MapperScan
package com.zimo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// 在引导类上添加SpringBootApplication注解
@SpringBootApplication
// 扫描mybatis所有的业务mapper接口
@MapperScan("com.zimo.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Spring Boot整合通用Mapper

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

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

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

<!--通用mapper-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.1.5</version>
</dependency>
  • 注意:一旦引入了通用Mapper的启动器,会覆盖Mybatis官方启动器的功能,因此需要移除对官方Mybatis启动器的依赖
  • UserMappper改造
package com.zimo.mapper;
import com.zimo.pojo.User;
import tk.mybatis.mapper.common.Mapper;

public interface UserMapper extends Mapper<User> {
}
  • 修改启动引导类
    • 在启动引导类上面的mapper扫描注解一定要修改为通用mapper的扫描注解
package com.zimo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
// 在引导类上添加SpringBootApplication注解
@SpringBootApplication
// 扫描mybatis所有的业务mapper接口
// @MapperScan("com.zimo.mapper")
// 使用tk的MapperScan
@MapperScan("com.zimo.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  • 修改User实体类
package com.zimo.pojo;
import lombok.Data;
import tk.mybatis.mapper.annotation.KeySql;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
/**
 * @author Liu_zimo
 * @version v0.1 by 2021/5/31 15:51
 */
// 在编译阶段会根据注解自动生成对应的方法; data包含get/set/hashCode/equals/toString等方法
@Data
@Table(name = "user")
public class User {
    @Id
    // 主键回填
    @KeySql(useGeneratedKeys = true)
    private Integer id;	// 假如这边使用int后面的selectByPrimaryKey(id)会查询不到数据
    @Column
    private String username;
    @Column
    private Date birthday;
    @Column
    private String sex;
    @Column
    private String address;
}
  • 改造UserService
package com.zimo.service;
import com.zimo.mapper.UserMapper;
import com.zimo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * 业务类
 * @author Liu_zimo
 * @version v0.1 by 2021/6/1 11:18
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    // 根据id查询
    public User queryById(int id){
        return userMapper.selectByPrimaryKey(id);
    }
    // 新增保存用户
    @Transactional  // 添加事务注解
    public void save(User user){
        // 选择性新增,如果属性为空,该属性不会出现在insert语句上
        userMapper.insertSelective(user);
    }
}

SpringBoot整合测试

  • 目标:可以访问处理器对应路径将数据库中的数据根据id查询
  • 分析:
    1. 改造HelloController,注入UserService利用其方法实现查询
    2. 启动项目进行测试http://localhost/user/用户id
package com.zimo.controller;
import com.zimo.pojo.User;
import com.zimo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
 * 处理器
 * @author Liu_zimo
 * @version v0.1 by 2021/5/28 16:59
 */
@RestController // 组合注解ResponseBody + Controller
public class HelloController {

    @Autowired
    private UserService userService;

    @GetMapping("/user/{id}")
    public User findUserById(@PathVariable int id){
        User user = userService.queryById(id);
        return user;
    }
}

使用Spring Boot整合Junit

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

  • 分析:

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>
package com.zimo.service;
import com.zimo.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import static org.junit.Assert.*;

/**
 * 测试类
 *
 * @author Liu_zimo
 * @version v0.1 by 2021/6/2 15:17
 */
@RunWith(SpringRunner.class)
@SpringBootTest	// 必须添加该标签
public class UserServiceTest {

    @Autowired
    private UserService userService;
    @Test
    public void queryById() {
        User user = userService.queryById(43);
        System.out.println(user);
    }

    @Test
    public void save() {
        User user = new User();
        user.setUsername("zimo");
        user.setBirthday(new Date());
        user.setSex("男");
        user.setAddress("上海");
        userService.save(user);
    }
}

使用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)
  • 添加启动器

<!--redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  • 配置application.yml
spring:
  redis:
    host: localhost
    port: 6379
  • 测试类
package com.zimo.redis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * 描述
 *
 * @author Liu_zimo
 * @version v0.1 by 2021/6/2 15:33
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class RedisTest {
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void test(){
        // 1 string 字符串
        redisTemplate.opsForValue().set("name", "zimo");
        redisTemplate.boundValueOps("name").set("zimo1");
        // 1.1 输出
        System.out.println("name :" + redisTemplate.opsForValue().get("name"));

        // 2 hash 散列
        redisTemplate.boundHashOps("hash").put("name", "zhangsan");
        redisTemplate.boundHashOps("hash").put("age", "18");
        // 2.1 获取所有域
        System.out.println("keys :" + redisTemplate.boundHashOps("hash").keys());
        // 2.2 获取所有值
        System.out.println("values :" + redisTemplate.boundHashOps("hash").values());

        // 3 list 列表
        redisTemplate.boundListOps("list").leftPush("c");
        redisTemplate.boundListOps("list").leftPush("b");
        redisTemplate.boundListOps("list").leftPush("a");
        // 3.1 输出所有
        System.out.println("list :" + redisTemplate.boundListOps("list").range(0, -1));

        // 4 set 集合
        redisTemplate.boundSetOps("set").add("a","b","c");
        // 输出
        System.out.println("set :" + redisTemplate.boundSetOps("set").members());

        // 5 sorted set 有序集合
        redisTemplate.boundZSetOps("zset").add("a", 30);
        redisTemplate.boundZSetOps("zset").add("b", 10);
        redisTemplate.boundZSetOps("zset").add("c", 20);
        // 输出
        System.out.println("zset :" + redisTemplate.boundZSetOps("zset").range(0, -1));
    }
}

部署Spring Boot项目

  • 目标:将Spring Boot项目使用maven指令打成jar包并运行测试
  • 分析:
    1. 需要添加打包组件将项目中的资源、配置、依赖包打到一个jar包中;可以使用maven的package
    2. 部署:java -jar 包名
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

插件

在应用spring boot工程的时候;一般情况下都需要创建启动引导类Application.java和application.yml配置文件,而且内容都是一样的;为了便捷可以安装一个IDEA的插件JBLSpringBootAppGen在项目上右击之后可以自动生成启动引导类Application.javaapplication.yml配置文件。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柳子陌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值