1 自定义启动 Banner

  • 在启动 SpringBoot 项目的时候可以发现有如下的一条启动的信息:

1.png

2.png

  • 在底部提供的是一个文本,可以将文本复制到项目的 resources 目录中(src/main/resources/banner.txt),banner.txt 是一个固定的名称,不可修改。
  1. _____ .__
  2. _/ ____\____ |__|______ ___.__. ________________
  3. \ __\\__ \ | \_ __ < | | _/ __ \_ __ \__ \
  4. | | / __ \| || | \/\___ | \ ___/| | \// __ \_
  5. |__| (____ /__||__| / ____| /\ \___ >__| (____ /
  6. \/ \/ \/ \/ \/
  • 随后重新启动一下 SpringBoot 程序,就可以发现已经更换了对应的 Banner 信息了。

3.png

  • 仅仅这样还不够,我们如何实现和 SpringBoot 默认 Banner 的实现效果?
  • ① 在 banner.txt 中可以输出一些全局变量,比如:
    • ${application.version}:用来获取 MANIFEST.MF 文件中的版本号。
    • ${spring-boot.version}:Spring Boot 版本号。
    • ${spring-boot.formatted-version}:格式化后的 ${spring-boot.version} 版本信息。
  1. _____ .__
  2. _/ ____\____ |__|______ ___.__. ________________
  3. \ __\\__ \ | \_ __ < | | _/ __ \_ __ \__ \
  4. | | / __ \| || | \/\___ | \ ___/| | \// __ \_
  5. |__| (____ /__||__| / ____| /\ \___ >__| (____ /
  6. \/ \/ \/ \/ \/
  7. ::Spring Boot:: ${spring-boot.formatted-version}

4.png

  • ② SpringBoot 默认 Banner 中的 Spring Boot 是有颜色的,那么我们可以下面的三个枚举类来控制 banner 文字的样式:
    • AnsiColor:用来设定字符的前景色。
    • AnsiBackground:用来设定字符的背景色。
    • AnsiStyle:用来控制加粗、斜体、下划线等等。
  1. _____ .__
  2. _/ ____\____ |__|______ ___.__. ________________
  3. \ __\\__ \ | \_ __ < | | _/ __ \_ __ \__ \
  4. | | / __ \| || | \/\___ | \ ___/| | \// __ \_
  5. |__| (____ /__||__| / ____| /\ \___ >__| (____ /
  6. \/ \/ \/ \/ \/
  7. ${AnsiColor.GREEN} ::Spring Boot:: ${AnsiColor.BLACK}${spring-boot.formatted-version}

5.png

  • 其实,之所以可以通过 banner.txt 实现自定义 Banner 是因为 Spring Boot 框架在启动时会按照以下顺序,查找 banner 信息:
    • 先在 classpath 下找 文件 banner.gif 或 banner.jpg 或 banner.png ,先找到谁就用谁;
    • 以上都没有就在 classpath 下找 banner.txt;
    • 如果都没找到才会使用默认的 SpringBootBanner。
  • 可以从 SpringApplicationBannerPrinter 的源码中知道上面的信息:
  1. package org.springframework.boot;
  2. class SpringApplicationBannerPrinter {
  3. static final String BANNER_LOCATION_PROPERTY = "spring.banner.location";
  4. static final String BANNER_IMAGE_LOCATION_PROPERTY = "spring.banner.image.location";
  5. static final String DEFAULT_BANNER_LOCATION = "banner.txt";
  6. static final String[] IMAGE_EXTENSION = { "gif", "jpg", "png" };
  7. private static final Banner DEFAULT_BANNER = new SpringBootBanner();
  8. private final ResourceLoader resourceLoader;
  9. private final Banner fallbackBanner;
  10. // 其他略
  11. private Banner getBanner(Environment environment) {
  12. Banners banners = new Banners();、
  13. // 获取图片形式 banner
  14. banners.addIfNotNull(getImageBanner(environment));
  15. // 获取文字形式 banner
  16. banners.addIfNotNull(getTextBanner(environment));
  17. if (banners.hasAtLeastOneBanner()) {
  18. return banners;
  19. }
  20. if (this.fallbackBanner != null) {
  21. return this.fallbackBanner;
  22. }
  23. return DEFAULT_BANNER;
  24. }
  25. private Banner getTextBanner(Environment environment) {
  26. String location = environment.getProperty(BANNER_LOCATION_PROPERTY, DEFAULT_BANNER_LOCATION);
  27. Resource resource = this.resourceLoader.getResource(location);
  28. try {
  29. if (resource.exists() && !resource.getURL().toExternalForm().contains("liquibase-core")) {
  30. return new ResourceBanner(resource);
  31. }
  32. }
  33. catch (IOException ex) {
  34. // Ignore
  35. }
  36. return null;
  37. }
  38. private Banner getImageBanner(Environment environment) {
  39. String location = environment.getProperty(BANNER_IMAGE_LOCATION_PROPERTY);
  40. if (StringUtils.hasLength(location)) {
  41. Resource resource = this.resourceLoader.getResource(location);
  42. return resource.exists() ? new ImageBanner(resource) : null;
  43. }
  44. for (String ext : IMAGE_EXTENSION) {
  45. Resource resource = this.resourceLoader.getResource("banner." + ext);
  46. if (resource.exists()) {
  47. return new ImageBanner(resource);
  48. }
  49. }
  50. return null;
  51. }
  52. }
  • 除了采用以上的方式实现了 Banner 的配置之外,实际上也可以在项目中基于 Bean 的方式来进行配置(如果使用的是一个文本,那么 Banner 就会固定一个,但是如果说希望可以进行不同的 Banner 的切换,那么就可以基于 Bean 的方式来进行配置了),如果要想配置启动的 Banner 的文字,最终的一个接口就是 org.springframework.boot.Banner 接口。
  1. package org.springframework.boot;
  2. import java.io.PrintStream;
  3. import org.springframework.core.env.Environment;
  4. @FunctionalInterface // 函数式接口
  5. public interface Banner { // 由 SpringBoot 提供的内部接口
  6. /**
  7. * 通过指定的 PrintStream 来实现启动 Banner 的输出
  8. * @param environment 项目启动的时候指定的 profile
  9. * @param sourceClass 应用的程序类
  10. * @param out 实现 Banner 的信息输出
  11. */
  12. void printBanner(Environment environment, Class<?> sourceClass, PrintStream out);
  13. /**
  14. * Banner 启动的模式
  15. */
  16. enum Mode {
  17. OFF, // 不输出 Banner 的信息
  18. CONSOLE, // 在控制台输出 Banner
  19. LOG // 在日志中输出 Banner
  20. }
  21. }
  • 下面可以考虑实现一个 Banner 接口的实现类,随后基于一个随机数的方式在每次启动的时候实现动态 Banner 的配置,这样一来 src/main/resources 目录下的 banner.txt 就不需要再使用了,删除即可。
  • 定义一个 Banner 接口的实现类:
  1. package com.github.fairy.era.banner;
  2. import org.springframework.boot.Banner;
  3. import org.springframework.core.env.Environment;
  4. import java.io.PrintStream;
  5. import java.security.SecureRandom;
  6. /**
  7. * 实现自定义 Banner 输出
  8. *
  9. * @author 许大仙
  10. * @since 2022-01-03 06-34
  11. */
  12. public class FairyBanner implements Banner {
  13. private static final String[] BANNER = {
  14. " _____ .__",
  15. "_/ ____\\____ |__|______ ___.__. ________________",
  16. "\\ __\\\\__ \\ | \\_ __ < | | _/ __ \\_ __ \\__ \\",
  17. " | | / __ \\| || | \\/\\___ | \\ ___/| | \\// __ \\_",
  18. " |__| (____ /__||__| / ____| /\\ \\___ >__| (____ /",
  19. " \\/ \\/ \\/ \\/ \\/"
  20. };
  21. private static final String[] EDU_BANNER = {
  22. " .___ _____ .__ ",
  23. " ____ __| _/_ __ _/ ____\\____ |__|______ ___.__. ________________ ",
  24. "_/ __ \\ / __ | | \\ \\ __\\\\__ \\ | \\_ __ < | | _/ __ \\_ __ \\__ \\ ",
  25. "\\ ___// /_/ | | / | | / __ \\| || | \\/\\___ | \\ ___/| | \\// __ \\_",
  26. " \\___ >____ |____/ /\\ |__| (____ /__||__| / ____| /\\ \\___ >__| (____ /",
  27. " \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/"
  28. };
  29. private static final String COMMON_BANNER = "许大仙";
  30. private static final SecureRandom random = new SecureRandom();
  31. @Override
  32. public void printBanner(Environment environment, Class<?> sourceClass, PrintStream out) {
  33. // 输出换行
  34. out.println();
  35. // 生成一个 0 ~ 9 的随机数
  36. int num = random.nextInt(10);
  37. if (0 == num) {
  38. for (String line : BANNER) {
  39. out.println(line);
  40. }
  41. } else if (num % 2 == 0) {
  42. for (String line : EDU_BANNER) {
  43. out.println(line);
  44. }
  45. } else {
  46. out.println(COMMON_BANNER);
  47. }
  48. // 输出换行
  49. out.println("");
  50. out.flush();
  51. }
  52. }
  • 此时的配置类如果想在 SpringBoot 中生效,就需要修改 SpringBoot 的启动类:
  1. package com.github.fairy.era;
  2. import com.github.fairy.era.banner.FairyBanner;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. /**
  6. * 启动类
  7. *
  8. * @author 许大仙
  9. * @version 1.0
  10. * @since 2021-12-31 09:14
  11. */
  12. @SpringBootApplication
  13. public class Application {
  14. public static void main(String[] args) {
  15. // 获取实例化对象
  16. SpringApplication springApplication = new SpringApplication(Application.class);
  17. // 设置 Banner
  18. springApplication.setBanner(new FairyBanner());
  19. // 运行 SpringBoot 程序
  20. springApplication.run(args);
  21. }
  22. }
  • 既然已经可以实现 Banner 的生成了,那么就可以考虑进行 Banner 模式的配置了,需要修改 SpringBoot 的启动类:
  1. package com.github.fairy.era;
  2. import com.github.fairy.era.banner.FairyBanner;
  3. import org.springframework.boot.Banner;
  4. import org.springframework.boot.SpringApplication;
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;
  6. /**
  7. * 启动类
  8. *
  9. * @author 许大仙
  10. * @version 1.0
  11. * @since 2021-12-31 09:14
  12. */
  13. @SpringBootApplication
  14. public class Application {
  15. public static void main(String[] args) {
  16. // 获取实例化对象
  17. SpringApplication springApplication = new SpringApplication(Application.class);
  18. // 设置 Banner
  19. springApplication.setBanner(new FairyBanner());
  20. // Banner.Mode 的配置:关闭 Banner 的输出
  21. springApplication.setBannerMode(Banner.Mode.OFF);
  22. // 运行 SpringBoot 程序
  23. springApplication.run(args);
  24. }
  25. }
  • 在实际开发中,很少有人愿意做这么繁琐的 Banner 的处理,此处演示自定义 Banner 的目的就是为了后面的 SpringBoot 启动流程而准备的,因为源代码中就有 Banner 接口。

2 导入 Spring 配置文件(不推荐)

2.1 概述

  • 在进行 SpringBoot 项目开发的时候,一般常用的做法就是在 @SpringBootApplication 注解所在包及其子包下,保存有其他的相关组件,那么下面就按照 SpringBoot 的约定来实现一个业务层的咖啡啊。

2.2 micro-web 子模块

  • 创建一个消息处理的业务接口:
  1. package com.github.fairy.era.service;
  2. /**
  3. * @author 许大仙
  4. * @since 2022-01-03 07-06
  5. */
  6. public interface IMessageService {
  7. String echo(String msg);
  8. }
  • 按照 Spring 的处理方法来定义业务接口的子类,同时使用 @Service 注解进行配置。
  1. package com.github.fairy.era.service.impl;
  2. import com.github.fairy.era.service.IMessageService;
  3. import org.springframework.stereotype.Service;
  4. /**
  5. * @author 许大仙
  6. * @since 2022-01-03 07-52
  7. */
  8. @Service
  9. public class MessageServiceImpl implements IMessageService {
  10. @Override
  11. public String echo(String msg) {
  12. return "【ECHO】" + msg;
  13. }
  14. }
  • 在 MessageHandler 程序类之中利用 IOC 机制实现 IMessageService 接口的注入:
  1. package com.github.fairy.era.web;
  2. import com.github.fairy.era.service.IMessageService;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. /**
  10. * @author 许大仙
  11. * @since 2022-01-03 07-55
  12. */
  13. @RestController
  14. @RequestMapping("/message")
  15. public class MessageHandler {
  16. // 获取日志对象
  17. private static final Logger LOGGER = LoggerFactory.getLogger(MessageHandler.class);
  18. @Autowired
  19. private IMessageService messageService;
  20. @GetMapping("/echo")
  21. public String echo(String msg) {
  22. LOGGER.info("接收 msg 的请求参数,参数内容是 {}", msg);
  23. return this.messageService.echo(msg);
  24. }
  25. }

6.png

  • 以上的处理操作是根据 Spring 所提供的一些 Bean 配置注解的方式来完成的,此时的程序是新编写的,所以使用注解没什么问题。
  • 但是,如果说有这么一种情况,在 2010 年的时候公司投资了一个项目(SSH、SSM),这个项目现在要求使用 SpringBoot 框架进行二期开发,传统项目里面已经采用了大量的 Spring 配置文件模式(XML)来进行项目诶只,如果将其更换为 SpringBoot ,所需要修改的就会非常的多,为了解决这个问题,在 SpringBoot 里面支持开发者导入 XML 配置文件。
  • 模拟传统的 XML 形式的 Spring 项目:
    • ① 删除 MessageServiceImpl 实现类的 @Service 注解。 ```java package com.github.fairy.era.service.impl;

import com.github.fairy.era.service.IMessageService;

/**

  • @author 许大仙
  • @since 2022-01-03 07-52 */ public class MessageServiceImpl implements IMessageService { @Override public String echo(String msg) {

    1. return "【ECHO】" + msg;

    } }

    1. - src/main/resource 目录之中创建 META-INF/spring/spring-service.xml 配置文件,并进行 MessageServiceImpl Bean 的配置:
    2. ```xml
    3. <?xml version="1.0" encoding="UTF-8"?>
    4. <beans xmlns="http://www.springframework.org/schema/beans"
    5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    7. <bean id="messageService" class="com.github.fairy.era.service.impl.MessageServiceImpl"></bean>
    8. </beans>
  • 如果要想将当前的配置文件和 SpringBoot 项目整合到一起,那么就需要在启动类中追加响应的配置注解 @ImportSource ,该注解可以引入要导入的 Spring 配置文件:
  1. package com.github.fairy.era;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.context.annotation.ImportResource;
  5. /**
  6. * 启动类
  7. *
  8. * @author 许大仙
  9. * @version 1.0
  10. * @since 2021-12-31 09:14
  11. */
  12. @ImportResource(locations = "classpath:META-INF/spring/spring-*.xml")
  13. @SpringBootApplication
  14. public class Application {
  15. public static void main(String[] args) {
  16. SpringApplication.run(Application.class, args);
  17. }
  18. }
  • 配置完成之后,需要重新启动 SpringBoot 应用程序。

3 项目热部署

3.1 概述

  • 在进行 Java 项目开发过程中,最痛苦的一件事情就是每次修改代码之后都需要重启服务器,为了解决这个问题,在 SpringBoot 就提供了所谓的热加载机制,只要程序发生变更,就会自动进行 SpringBoot 容器的重新启动,而后加载新的配置。

3.2 microboot 项目

  • 如果要想解决这种自动加载的问题,需要在项目中引入如下的依赖:
  1. implementation group: 'org.springframework.boot', name: 'spring-boot-devtools', version: '2.4.3'
  • 因为目前项目是通过 Gradle 来进行依赖库的管理,所以可以修改 microboot 项目的 build.gradle 文件在公共模块依赖处进行依赖配置:
  1. subprojects { // 子模块的配置
  2. dependencies { // 公共依赖管理
  3. implementation group: 'org.springframework.boot', name: 'spring-boot-devtools' // 允许进行项目的热部署
  4. }
  5. // 其他略
  6. }
  • microboot 项目的完整的 build.gradle 文件内容如下:
  1. buildscript { // 定义脚本使用资源
  2. apply from: 'dependencies.gradle' // 引入所需要的依赖库文件
  3. repositories { // 脚本资源仓库
  4. maven {
  5. url 'https://maven.aliyun.com/repository/gradle-plugin'
  6. }
  7. }
  8. dependencies { // 依赖管理
  9. classpath libraries.'spring-boot-gradle-plugin'
  10. }
  11. }
  12. apply from: 'dependencies.gradle' // 引入所需要的依赖库文件
  13. allprojects { // 所有模块/项目的通用配置
  14. apply plugin: 'idea'
  15. apply plugin: 'java'
  16. apply plugin: 'java-library'
  17. group project_group // 组织名称
  18. version project_version // 版本号
  19. sourceCompatibility = project_jdk // 本次的项目都是基于 JDK-8 的版本
  20. targetCompatibility = project_jdk // 本次的项目都是基于 JDK-8 的版本
  21. }
  22. subprojects { // 子模块的配置
  23. apply plugin: 'org.springframework.boot' // 将版本编号配置在插件内部
  24. apply plugin: 'io.spring.dependency-management' // 由此插件负责版本号的维护
  25. repositories { // 仓库配置
  26. maven { // 阿里云的 Maven 仓库
  27. url 'https://maven.aliyun.com/repository/public/'
  28. }
  29. mavenCentral() // 默认情况下所提供的是 Maven 的中央仓库
  30. }
  31. dependencies { // 公共依赖管理
  32. implementation group: 'org.springframework.boot', name: 'spring-boot-devtools' // 允许进行项目的热部署
  33. }
  34. test {
  35. useJUnitPlatform()
  36. }
  37. sourceSets { // 建立源代码的目录集合
  38. main {
  39. java {
  40. srcDirs = ['src/main/java']
  41. }
  42. resources {
  43. srcDirs = ['src/main/resources']
  44. }
  45. }
  46. test {
  47. java {
  48. srcDirs = ['src/test/java']
  49. }
  50. resources {
  51. srcDirs = ['src/test/resources']
  52. }
  53. }
  54. }
  55. gradle.taskGraph.whenReady { // 在所有的操作准备好之后触发
  56. tasks.each { task ->
  57. if (task.name.contains('test')) { // 如果发现有 test 任务,就跳过
  58. task.enabled = true // 当前任务不执行
  59. }
  60. }
  61. }
  62. // 最终生成的 jar 文件名称:baseName-version-classifier.extension
  63. task sourceJar(type: Jar, dependsOn: classes) { // 定义一个源代码的打包任务,并依赖于 classes 这种 Gradle 内置的任务
  64. archiveClassifier.set 'sources' // 文件的分类
  65. from sourceSets.main.allSource // 所有源代码的读取路径
  66. }
  67. task javadocTask(type: Javadoc) {
  68. source sourceSets.main.allJava // 定义所有的 Java 源代码的路径
  69. }
  70. tasks.withType(Javadoc) { // 文档生成一定要有乱码处理
  71. options.encoding = "UTF-8"
  72. }
  73. tasks.withType(JavaCompile) { // 针对程序编译的任务进行配置
  74. options.encoding = "UTF-8"
  75. }
  76. task javadocJar(type: Jar, dependsOn: javadocTask) { // 先生成 javadoc,才可以打包
  77. archiveClassifier.set 'javadoc' // 文件的分类
  78. from javadocTask.destinationDir // 通过 javaDocTask 任务中找到目标路径
  79. }
  80. artifacts { // 最终的打包操作任务
  81. archives sourceJar
  82. archives javadocJar
  83. }
  84. [compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
  85. }
  86. project(':microboot-common') { // 设置子项目的配置,独享配置
  87. dependencies { // 配置子模块依赖
  88. }
  89. }
  90. project(':microboot-web') { // 设置子项目的配置,独享配置
  91. dependencies { // 配置子模块依赖
  92. implementation(project(':microboot-common')) // 引入其他子模块
  93. implementation 'org.springframework.boot:spring-boot-starter-web' // 引入 SpringBoot 的 web 的依赖
  94. }
  95. gradle.taskGraph.whenReady { // 在所有的操作准备好之后触发
  96. tasks.each { task ->
  97. if (task.name.contains('javadoc')) { // 如果发现有 javadoc 任务,就跳过
  98. task.enabled = false // 当前任务不执行
  99. }
  100. }
  101. }
  102. }

3.3 IDEA 工具

  • 如果使用的开发工具是 IDEA ,还需要进行如下的配置。

7.png

  • 仅仅配置以上的选项还不能支持自动的部署处理,如果要想实现部署的自动配置,在 IDEA 中还需要进行一些配置的注册,Win 平台下按 Ctrl + Shift + Alt + / 的快捷键。

8.gif

  • 不过,在最新的版本的 IDEA 工具中已经内置开启了该选项参数了。

11.png

  • 当所有的配置都完成之后,最好重新启动 IDEA ,这样在每次代码修改并且保存之后都会自动的重新启动 SpringBoot 的容器(并不是整个容器的重新启动,而是内部的部分程序类的启动)。
  • 激活方式:IDEA 失去焦点 5 秒后启动热部署。

3.4 热部署范围配置

  • 默认不触发重启的目录列表:
    • /META-INF/maven
    • /META-INF/resources
    • /resources
    • /static
    • /public
    • /templates
    • ……
  • 自定义不参与重启排除项:
  1. spring:
  2. devtools:
  3. restart:
  4. # 设置不参与热部署的文件或文件夹
  5. exclude: static/**,public/**,config/application.yml

3.5 关闭热部署

  • ① 在 application.yml 中通过配置关闭热部署:
  1. spring:
  2. devtools:
  3. restart:
  4. enabled: false # 关闭热部署
  • ② 设置高优先级属性禁用热部署:
  1. package com.github.fairy.era;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. /**
  5. * @author 许大仙
  6. */
  7. @SpringBootApplication
  8. public class Application {
  9. public static void main(String[] args) {
  10. System.setProperty("spring.devtools.restart.enabled", "false");
  11. SpringApplication.run(Application.class, args);
  12. }
  13. }

4 整合 Junit 5 测试工具

4.1 概述

  • 在学习 Spring 框架的时候,我们知道在 Spring 里面为了方便用户的测试提供了一个 spring-test 的依赖,那么在进行 SpringBoot 项目开发的时候由于运行的方式有一些变更,所以在 SpringBoot 中提供了 spring-boot-starter-test 的依赖,其内部采用的测试组件为 Junit 5 。

4.2 microboot 项目

  • 在 build.gradle 配置文件中的对 microboot-web 进行依赖管理:
  1. subprojects { // 子模块的配置
  2. dependencies { // 公共依赖管理
  3. implementation group: 'org.springframework.boot', name: 'spring-boot-devtools' // 允许进行项目的热部署
  4. testImplementation 'org.springframework.boot:spring-boot-starter-test' //引入 SpringBoot 的 test 的依赖
  5. }
  6. }
  • 完整的 build.gradle 文件内容如下:
  1. buildscript { // 定义脚本使用资源
  2. apply from: 'dependencies.gradle' // 引入所需要的依赖库文件
  3. repositories { // 脚本资源仓库
  4. maven {
  5. url 'https://maven.aliyun.com/repository/gradle-plugin'
  6. }
  7. }
  8. dependencies { // 依赖管理
  9. classpath libraries.'spring-boot-gradle-plugin'
  10. }
  11. }
  12. apply from: 'dependencies.gradle' // 引入所需要的依赖库文件
  13. allprojects { // 所有模块/项目的通用配置
  14. apply plugin: 'idea'
  15. apply plugin: 'java'
  16. apply plugin: 'java-library'
  17. group project_group // 组织名称
  18. version project_version // 版本号
  19. sourceCompatibility = project_jdk // 本次的项目都是基于 JDK-8 的版本
  20. targetCompatibility = project_jdk // 本次的项目都是基于 JDK-8 的版本
  21. }
  22. subprojects { // 子模块的配置
  23. apply plugin: 'org.springframework.boot' // 将版本编号配置在插件内部
  24. apply plugin: 'io.spring.dependency-management' // 由此插件负责版本号的维护
  25. repositories { // 仓库配置
  26. maven { // 阿里云的 Maven 仓库
  27. url 'https://maven.aliyun.com/repository/public/'
  28. }
  29. mavenCentral() // 默认情况下所提供的是 Maven 的中央仓库
  30. }
  31. dependencies { // 公共依赖管理
  32. implementation group: 'org.springframework.boot', name: 'spring-boot-devtools' // 允许进行项目的热部署
  33. testImplementation 'org.springframework.boot:spring-boot-starter-test' //引入 SpringBoot 的 test 的依赖
  34. }
  35. test {
  36. useJUnitPlatform()
  37. }
  38. sourceSets { // 建立源代码的目录集合
  39. main {
  40. java {
  41. srcDirs = ['src/main/java']
  42. }
  43. resources {
  44. srcDirs = ['src/main/resources']
  45. }
  46. }
  47. test {
  48. java {
  49. srcDirs = ['src/test/java']
  50. }
  51. resources {
  52. srcDirs = ['src/test/resources']
  53. }
  54. }
  55. }
  56. gradle.taskGraph.whenReady { // 在所有的操作准备好之后触发
  57. tasks.each { task ->
  58. if (task.name.contains('test')) { // 如果发现有 test 任务,就跳过
  59. task.enabled = true // 当前任务不执行
  60. }
  61. }
  62. }
  63. // 最终生成的 jar 文件名称:baseName-version-classifier.extension
  64. task sourceJar(type: Jar, dependsOn: classes) { // 定义一个源代码的打包任务,并依赖于 classes 这种 Gradle 内置的任务
  65. archiveClassifier.set 'sources' // 文件的分类
  66. from sourceSets.main.allSource // 所有源代码的读取路径
  67. }
  68. task javadocTask(type: Javadoc) {
  69. source sourceSets.main.allJava // 定义所有的 Java 源代码的路径
  70. }
  71. tasks.withType(Javadoc) { // 文档生成一定要有乱码处理
  72. options.encoding = "UTF-8"
  73. }
  74. tasks.withType(JavaCompile) { // 针对程序编译的任务进行配置
  75. options.encoding = "UTF-8"
  76. }
  77. task javadocJar(type: Jar, dependsOn: javadocTask) { // 先生成 javadoc,才可以打包
  78. archiveClassifier.set 'javadoc' // 文件的分类
  79. from javadocTask.destinationDir // 通过 javaDocTask 任务中找到目标路径
  80. }
  81. artifacts { // 最终的打包操作任务
  82. archives sourceJar
  83. archives javadocJar
  84. }
  85. [compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
  86. }
  87. project(':microboot-common') { // 设置子项目的配置,独享配置
  88. dependencies { // 配置子模块依赖
  89. }
  90. }
  91. project(':microboot-web') { // 设置子项目的配置,独享配置
  92. dependencies { // 配置子模块依赖
  93. implementation(project(':microboot-common')) // 引入其他子模块
  94. implementation 'org.springframework.boot:spring-boot-starter-web' // 引入 SpringBoot 的 web 的依赖
  95. }
  96. gradle.taskGraph.whenReady { // 在所有的操作准备好之后触发
  97. tasks.each { task ->
  98. if (task.name.contains('javadoc')) { // 如果发现有 javadoc 任务,就跳过
  99. task.enabled = false // 当前任务不执行
  100. }
  101. }
  102. }
  103. }
  • 如果要想让当前的配置在 IDEA 中生效,则一定要进行 Gradle 的刷新(新版本的 IDEA 中不会自动更新 Gradle 的依赖了)。

4.3 microboot-web 子模块

  • 此时一切的环境就已经配置成功了,随后就可以在项目中进行 Junit 测试类的编写了。

  • 示例:

  1. package com.github.fairy.era;
  2. import com.github.fairy.era.web.MessageHandler;
  3. import org.junit.jupiter.api.AfterEach;
  4. import org.junit.jupiter.api.BeforeEach;
  5. import org.junit.jupiter.api.Test;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. /**
  9. * @author 许大仙
  10. * @version 1.0
  11. * @since 2022-01-04 09:36
  12. */
  13. @SpringBootTest
  14. public class ApplicationTest {
  15. @Autowired
  16. private MessageHandler messageHandler;
  17. @BeforeEach
  18. public void beforeEach() {
  19. System.out.println("【@BeforeEach】ApplicationTest 开始执行测试操作");
  20. }
  21. @AfterEach
  22. public void afterEach() {
  23. System.out.println("【@AfterEach】ApplicationTest 测试完成");
  24. }
  25. @Test
  26. public void test() {
  27. String msg = this.messageHandler.echo("你好啊");
  28. System.out.println("msg = " + msg); // msg = 【ECHO】SpringBoot你好啊
  29. }
  30. }

5 Lombok

5.1 概述

  • 在最早学习 Java 基础的时候,我们学习到类的时候就学习了封装,而后就需要开发者手工实现 setter 和 getter ,后来到了开发工具支持的年代(Eclipse 或 IDEA),这些开发工具可以帮助使用者自动生成这些 setter 和 getter 等方法。
  • 原始的 setter 和 getter 生成:
  1. package com.github.fairy.era.vo;
  2. /**
  3. * @author 许大仙
  4. * @version 1.0
  5. * @since 2022-01-04 11:01
  6. */
  7. public class Dept {
  8. private Integer deptNo;
  9. private String deptName;
  10. private String deptLocation;
  11. public Integer getDeptNo() {
  12. return deptNo;
  13. }
  14. public void setDeptNo(Integer deptNo) {
  15. this.deptNo = deptNo;
  16. }
  17. public String getDeptName() {
  18. return deptName;
  19. }
  20. public void setDeptName(String deptName) {
  21. this.deptName = deptName;
  22. }
  23. public String getDeptLocation() {
  24. return deptLocation;
  25. }
  26. public void setDeptLocation(String deptLocation) {
  27. this.deptLocation = deptLocation;
  28. }
  29. }
  • 每次都需要重复的定义属性,而后按照既定的规则来重复的生成 setter 和 getter ,实在是太繁琐了,于是 Lombok 应运而生,它可以通过注解的形式自动生成相关类的结构。
  • 如果要想正确的使用该插件,除了项目本身的环境支持外,还需要在开发工具(IDEA)中安装对应的插件,幸运的是,最新版的 IDEA 已经集成了该插件。
  • IDEA 需要启用注解处理。

9.png

5.2 Lombok 支持的注解

10.png

5.3 microboot 项目

  • 如果要想实现当前的自动代码生成的处理操作,则一定要引入 lombok 的依赖:
  1. compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.18.22'
  • 由于各个项目模块都有可能存在这种自动生成类结构的需求,那么最佳的做法就是在公共的依赖库之中进行 Lombok 的配置, 此时的配置需要准备两种不同的环境:编译生效和注解生效。
  • 修改 microboot 项目的 build.gradle 文件在公共模块依赖处进行依赖配置:
  1. subprojects { // 子模块的配置
  2. dependencies { // 公共依赖管理
  3. implementation group: 'org.springframework.boot', name: 'spring-boot-devtools' // 允许进行项目的热部署
  4. testImplementation 'org.springframework.boot:spring-boot-starter-test' //引入 SpringBoot 的 test 的依赖
  5. // lombok
  6. compileOnly 'org.projectlombok:lombok' // 编译生效
  7. annotationProcessor 'org.projectlombok:lombok' // 注解生效
  8. testCompileOnly 'org.projectlombok:lombok' // 编译生效
  9. testAnnotationProcessor 'org.projectlombok:lombok' // 注解生效
  10. }
  11. }
  • 完整的 build.gradle 配置文件:
  1. buildscript { // 定义脚本使用资源
  2. apply from: 'dependencies.gradle' // 引入所需要的依赖库文件
  3. repositories { // 脚本资源仓库
  4. maven {
  5. url 'https://maven.aliyun.com/repository/gradle-plugin'
  6. }
  7. }
  8. dependencies { // 依赖管理
  9. classpath libraries.'spring-boot-gradle-plugin'
  10. }
  11. }
  12. apply from: 'dependencies.gradle' // 引入所需要的依赖库文件
  13. allprojects { // 所有模块/项目的通用配置
  14. apply plugin: 'idea'
  15. apply plugin: 'java'
  16. apply plugin: 'java-library'
  17. group project_group // 组织名称
  18. version project_version // 版本号
  19. sourceCompatibility = project_jdk // 本次的项目都是基于 JDK-8 的版本
  20. targetCompatibility = project_jdk // 本次的项目都是基于 JDK-8 的版本
  21. }
  22. subprojects { // 子模块的配置
  23. apply plugin: 'org.springframework.boot' // 将版本编号配置在插件内部
  24. apply plugin: 'io.spring.dependency-management' // 由此插件负责版本号的维护
  25. repositories { // 仓库配置
  26. maven { // 阿里云的 Maven 仓库
  27. url 'https://maven.aliyun.com/repository/public/'
  28. }
  29. mavenCentral() // 默认情况下所提供的是 Maven 的中央仓库
  30. }
  31. dependencies { // 公共依赖管理
  32. implementation group: 'org.springframework.boot', name: 'spring-boot-devtools' // 允许进行项目的热部署
  33. testImplementation 'org.springframework.boot:spring-boot-starter-test' //引入 SpringBoot 的 test 的依赖
  34. // lombok
  35. compileOnly 'org.projectlombok:lombok' // 编译生效
  36. annotationProcessor 'org.projectlombok:lombok' // 注解生效
  37. testCompileOnly 'org.projectlombok:lombok' // 编译生效
  38. testAnnotationProcessor 'org.projectlombok:lombok' // 注解生效
  39. }
  40. test {
  41. useJUnitPlatform()
  42. }
  43. sourceSets { // 建立源代码的目录集合
  44. main {
  45. java {
  46. srcDirs = ['src/main/java']
  47. }
  48. resources {
  49. srcDirs = ['src/main/resources']
  50. }
  51. }
  52. test {
  53. java {
  54. srcDirs = ['src/test/java']
  55. }
  56. resources {
  57. srcDirs = ['src/test/resources']
  58. }
  59. }
  60. }
  61. gradle.taskGraph.whenReady { // 在所有的操作准备好之后触发
  62. tasks.each { task ->
  63. if (task.name.contains('test')) { // 如果发现有 test 任务,就跳过
  64. task.enabled = true // 当前任务不执行
  65. }
  66. }
  67. }
  68. // 最终生成的 jar 文件名称:baseName-version-classifier.extension
  69. task sourceJar(type: Jar, dependsOn: classes) { // 定义一个源代码的打包任务,并依赖于 classes 这种 Gradle 内置的任务
  70. archiveClassifier.set 'sources' // 文件的分类
  71. from sourceSets.main.allSource // 所有源代码的读取路径
  72. }
  73. task javadocTask(type: Javadoc) {
  74. source sourceSets.main.allJava // 定义所有的 Java 源代码的路径
  75. }
  76. tasks.withType(Javadoc) { // 文档生成一定要有乱码处理
  77. options.encoding = "UTF-8"
  78. }
  79. tasks.withType(JavaCompile) { // 针对程序编译的任务进行配置
  80. options.encoding = "UTF-8"
  81. }
  82. task javadocJar(type: Jar, dependsOn: javadocTask) { // 先生成 javadoc,才可以打包
  83. archiveClassifier.set 'javadoc' // 文件的分类
  84. from javadocTask.destinationDir // 通过 javaDocTask 任务中找到目标路径
  85. }
  86. artifacts { // 最终的打包操作任务
  87. archives sourceJar
  88. archives javadocJar
  89. }
  90. [compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
  91. }
  92. project(':microboot-common') { // 设置子项目的配置,独享配置
  93. dependencies { // 配置子模块依赖
  94. }
  95. }
  96. project(':microboot-web') { // 设置子项目的配置,独享配置
  97. dependencies { // 配置子模块依赖
  98. implementation(project(':microboot-common')) // 引入其他子模块
  99. implementation 'org.springframework.boot:spring-boot-starter-web' // 引入 SpringBoot 的 web 的依赖
  100. }
  101. gradle.taskGraph.whenReady { // 在所有的操作准备好之后触发
  102. tasks.each { task ->
  103. if (task.name.contains('javadoc')) { // 如果发现有 javadoc 任务,就跳过
  104. task.enabled = false // 当前任务不执行
  105. }
  106. }
  107. }
  108. }

5.4 生成简单 Java 类结构

5.4.1 概述

  • 在任何一个项目中都会存在有大量的简单的 Java 类,而这些简单的 Java 类的定义结构是非常类似的,此时就可以直接通过 Lombok 来进行定义了。

5.4.2 microboot-web 子模块(@Data 注解)

  • 生成简单的 Java 类基本结构:
  1. package com.github.fairy.era.domain;
  2. import lombok.Data;
  3. import java.util.Date;
  4. /**
  5. * @author 许大仙
  6. * @version 1.0
  7. * @since 2022-01-04 13:35
  8. */
  9. @Data // 这就是一个 Lombok 注解,此注解使用的最频繁
  10. public class Message {
  11. private String title;
  12. private Date publishDate;
  13. private String content;
  14. }
  • 通过 IDEA 查看反编译生成的 class 文件,目录为 build/classes :
  1. //
  2. // Source code recreated from a .class file by IntelliJ IDEA
  3. // (powered by FernFlower decompiler)
  4. //
  5. package com.github.fairy.era.domain;
  6. import java.util.Date;
  7. public class Message {
  8. private String title;
  9. private Date publishDate;
  10. private String content;
  11. public Message() {
  12. }
  13. public String getTitle() {
  14. return this.title;
  15. }
  16. public Date getPublishDate() {
  17. return this.publishDate;
  18. }
  19. public String getContent() {
  20. return this.content;
  21. }
  22. public void setTitle(String title) {
  23. this.title = title;
  24. }
  25. public void setPublishDate(Date publishDate) {
  26. this.publishDate = publishDate;
  27. }
  28. public void setContent(String content) {
  29. this.content = content;
  30. }
  31. public boolean equals(Object o) {
  32. if (o == this) {
  33. return true;
  34. } else if (!(o instanceof Message)) {
  35. return false;
  36. } else {
  37. Message other = (Message)o;
  38. if (!other.canEqual(this)) {
  39. return false;
  40. } else {
  41. label47: {
  42. Object this$title = this.getTitle();
  43. Object other$title = other.getTitle();
  44. if (this$title == null) {
  45. if (other$title == null) {
  46. break label47;
  47. }
  48. } else if (this$title.equals(other$title)) {
  49. break label47;
  50. }
  51. return false;
  52. }
  53. Object this$publishDate = this.getPublishDate();
  54. Object other$publishDate = other.getPublishDate();
  55. if (this$publishDate == null) {
  56. if (other$publishDate != null) {
  57. return false;
  58. }
  59. } else if (!this$publishDate.equals(other$publishDate)) {
  60. return false;
  61. }
  62. Object this$content = this.getContent();
  63. Object other$content = other.getContent();
  64. if (this$content == null) {
  65. if (other$content != null) {
  66. return false;
  67. }
  68. } else if (!this$content.equals(other$content)) {
  69. return false;
  70. }
  71. return true;
  72. }
  73. }
  74. }
  75. protected boolean canEqual(Object other) {
  76. return other instanceof Message;
  77. }
  78. public int hashCode() {
  79. int PRIME = true;
  80. int result = 1;
  81. Object $title = this.getTitle();
  82. int result = result * 59 + ($title == null ? 43 : $title.hashCode());
  83. Object $publishDate = this.getPublishDate();
  84. result = result * 59 + ($publishDate == null ? 43 : $publishDate.hashCode());
  85. Object $content = this.getContent();
  86. result = result * 59 + ($content == null ? 43 : $content.hashCode());
  87. return result;
  88. }
  89. public String toString() {
  90. return "Message(title=" + this.getTitle() + ", publishDate=" + this.getPublishDate() + ", content=" + this.getContent() + ")";
  91. }
  92. }
  • 现在可以发现,只要在类中使用 @Data 注解,就可以自动的根据当前类中所定义的属性来生成相应的 setter、getter、toString()、equals()、hashCode() 等方法,而这些方法在最早的时候需要人工或开发工具帮助我们来生成。
  • 通过测试类对生成的方法进行测试:
  1. package com.github.fairy.era;
  2. import com.github.fairy.era.domain.Message;
  3. import org.junit.jupiter.api.Test;
  4. import org.springframework.boot.test.context.SpringBootTest;
  5. import java.util.Date;
  6. /**
  7. * @author 许大仙
  8. * @version 1.0
  9. * @since 2022-01-04 09:36
  10. */
  11. @SpringBootTest
  12. public class ApplicationTest {
  13. @Test
  14. public void test() {
  15. Message message = new Message();
  16. message.setTitle("你大爷的");
  17. message.setPublishDate(new Date());
  18. message.setContent("许大仙");
  19. System.out.println("message = " + message);
  20. }
  21. }
  • 测试结果:
  1. message = Message(title=你大爷的, publishDate=Tue Jan 04 13:49:11 CST 2022, content=许大仙)

5.4.3 microboot-web 子模块(@NonNull 注解)

  • 希望希望某些属性在进行对象构造的时候必须全部传递,即 Lombok 需要生成有参构造方法:
  1. package com.github.fairy.era.domain;
  2. import lombok.Data;
  3. import lombok.NonNull;
  4. /**
  5. * @author 许大仙
  6. * @version 1.0
  7. * @since 2022-01-04 13:51
  8. */
  9. @Data // 本身不会生成构造方法(默认的无参构造)
  10. public class Dept {
  11. @NonNull // 该属性不允许为空
  12. private String deptNo;
  13. @NonNull // 该属性不允许为空
  14. private String deptName;
  15. private String location;
  16. }
  • 通过 IDEA 查看反编译生成的 class 文件,目录为 build/classes :
  1. //
  2. // Source code recreated from a .class file by IntelliJ IDEA
  3. // (powered by FernFlower decompiler)
  4. //
  5. package com.github.fairy.era.domain;
  6. import lombok.NonNull;
  7. public class Dept {
  8. @NonNull
  9. private String deptNo;
  10. @NonNull
  11. private String deptName;
  12. private String location;
  13. public Dept(@NonNull String deptNo, @NonNull String deptName) { // 生成了有参构造
  14. if (deptNo == null) {
  15. throw new NullPointerException("deptNo is marked non-null but is null");
  16. } else if (deptName == null) {
  17. throw new NullPointerException("deptName is marked non-null but is null");
  18. } else {
  19. this.deptNo = deptNo;
  20. this.deptName = deptName;
  21. }
  22. }
  23. @NonNull
  24. public String getDeptNo() {
  25. return this.deptNo;
  26. }
  27. @NonNull
  28. public String getDeptName() {
  29. return this.deptName;
  30. }
  31. public String getLocation() {
  32. return this.location;
  33. }
  34. public void setDeptNo(@NonNull String deptNo) {
  35. if (deptNo == null) {
  36. throw new NullPointerException("deptNo is marked non-null but is null");
  37. } else {
  38. this.deptNo = deptNo;
  39. }
  40. }
  41. public void setDeptName(@NonNull String deptName) {
  42. if (deptName == null) {
  43. throw new NullPointerException("deptName is marked non-null but is null");
  44. } else {
  45. this.deptName = deptName;
  46. }
  47. }
  48. public void setLocation(String location) {
  49. this.location = location;
  50. }
  51. public boolean equals(Object o) {
  52. if (o == this) {
  53. return true;
  54. } else if (!(o instanceof Dept)) {
  55. return false;
  56. } else {
  57. Dept other = (Dept)o;
  58. if (!other.canEqual(this)) {
  59. return false;
  60. } else {
  61. label47: {
  62. Object this$deptNo = this.getDeptNo();
  63. Object other$deptNo = other.getDeptNo();
  64. if (this$deptNo == null) {
  65. if (other$deptNo == null) {
  66. break label47;
  67. }
  68. } else if (this$deptNo.equals(other$deptNo)) {
  69. break label47;
  70. }
  71. return false;
  72. }
  73. Object this$deptName = this.getDeptName();
  74. Object other$deptName = other.getDeptName();
  75. if (this$deptName == null) {
  76. if (other$deptName != null) {
  77. return false;
  78. }
  79. } else if (!this$deptName.equals(other$deptName)) {
  80. return false;
  81. }
  82. Object this$location = this.getLocation();
  83. Object other$location = other.getLocation();
  84. if (this$location == null) {
  85. if (other$location != null) {
  86. return false;
  87. }
  88. } else if (!this$location.equals(other$location)) {
  89. return false;
  90. }
  91. return true;
  92. }
  93. }
  94. }
  95. protected boolean canEqual(Object other) {
  96. return other instanceof Dept;
  97. }
  98. public int hashCode() {
  99. int PRIME = true;
  100. int result = 1;
  101. Object $deptNo = this.getDeptNo();
  102. int result = result * 59 + ($deptNo == null ? 43 : $deptNo.hashCode());
  103. Object $deptName = this.getDeptName();
  104. result = result * 59 + ($deptName == null ? 43 : $deptName.hashCode());
  105. Object $location = this.getLocation();
  106. result = result * 59 + ($location == null ? 43 : $location.hashCode());
  107. return result;
  108. }
  109. public String toString() {
  110. return "Dept(deptNo=" + this.getDeptNo() + ", deptName=" + this.getDeptName() + ", location=" + this.getLocation() + ")";
  111. }
  112. }

5.4.4 microboot-web 子模块(@NoArgsConstructor 注解)

  • 希望提供无参构造,那么直接在类上使用无参的构造注解 @NoArgsConstructor 注解即可。
  1. package com.github.fairy.era.domain;
  2. import lombok.Data;
  3. import lombok.NoArgsConstructor;
  4. import lombok.NonNull;
  5. /**
  6. * @author 许大仙
  7. * @version 1.0
  8. * @since 2022-01-04 14:02
  9. */
  10. @Data
  11. @NoArgsConstructor // 会为当前的类自动生成无参构造
  12. public class Emp {
  13. @NonNull // 一旦生成无参构造方法,这个注解就失效了
  14. private String empNo;
  15. @NonNull // 一旦生成无参构造方法,这个注解就失效了
  16. private String empName;
  17. private Double salary;
  18. }
  • 通过 IDEA 查看反编译生成的 class 文件,目录为 build/classes :
  1. //
  2. // Source code recreated from a .class file by IntelliJ IDEA
  3. // (powered by FernFlower decompiler)
  4. //
  5. package com.github.fairy.era.domain;
  6. import lombok.NonNull;
  7. public class Emp {
  8. @NonNull
  9. private String empNo;
  10. @NonNull
  11. private String empName;
  12. private Double salary;
  13. @NonNull
  14. public String getEmpNo() {
  15. return this.empNo;
  16. }
  17. @NonNull
  18. public String getEmpName() {
  19. return this.empName;
  20. }
  21. public Double getSalary() {
  22. return this.salary;
  23. }
  24. public void setEmpNo(@NonNull String empNo) {
  25. if (empNo == null) {
  26. throw new NullPointerException("empNo is marked non-null but is null");
  27. } else {
  28. this.empNo = empNo;
  29. }
  30. }
  31. public void setEmpName(@NonNull String empName) {
  32. if (empName == null) {
  33. throw new NullPointerException("empName is marked non-null but is null");
  34. } else {
  35. this.empName = empName;
  36. }
  37. }
  38. public void setSalary(Double salary) {
  39. this.salary = salary;
  40. }
  41. public boolean equals(Object o) {
  42. if (o == this) {
  43. return true;
  44. } else if (!(o instanceof Emp)) {
  45. return false;
  46. } else {
  47. Emp other = (Emp)o;
  48. if (!other.canEqual(this)) {
  49. return false;
  50. } else {
  51. label47: {
  52. Object this$salary = this.getSalary();
  53. Object other$salary = other.getSalary();
  54. if (this$salary == null) {
  55. if (other$salary == null) {
  56. break label47;
  57. }
  58. } else if (this$salary.equals(other$salary)) {
  59. break label47;
  60. }
  61. return false;
  62. }
  63. Object this$empNo = this.getEmpNo();
  64. Object other$empNo = other.getEmpNo();
  65. if (this$empNo == null) {
  66. if (other$empNo != null) {
  67. return false;
  68. }
  69. } else if (!this$empNo.equals(other$empNo)) {
  70. return false;
  71. }
  72. Object this$empName = this.getEmpName();
  73. Object other$empName = other.getEmpName();
  74. if (this$empName == null) {
  75. if (other$empName != null) {
  76. return false;
  77. }
  78. } else if (!this$empName.equals(other$empName)) {
  79. return false;
  80. }
  81. return true;
  82. }
  83. }
  84. }
  85. protected boolean canEqual(Object other) {
  86. return other instanceof Emp;
  87. }
  88. public int hashCode() {
  89. int PRIME = true;
  90. int result = 1;
  91. Object $salary = this.getSalary();
  92. int result = result * 59 + ($salary == null ? 43 : $salary.hashCode());
  93. Object $empNo = this.getEmpNo();
  94. result = result * 59 + ($empNo == null ? 43 : $empNo.hashCode());
  95. Object $empName = this.getEmpName();
  96. result = result * 59 + ($empName == null ? 43 : $empName.hashCode());
  97. return result;
  98. }
  99. public String toString() {
  100. return "Emp(empNo=" + this.getEmpNo() + ", empName=" + this.getEmpName() + ", salary=" + this.getSalary() + ")";
  101. }
  102. public Emp() { // 无参构造方法
  103. }
  104. }

5.4.5 microboot-web 子模块(@RequiredArgsConstructor 注解)

  • @RequiredArgsConstructor 注解会为 final 修改 或者 @NonNull 注解修改的属性生成构造方法。
  1. package com.github.fairy.era.domain;
  2. import lombok.NonNull;
  3. import lombok.RequiredArgsConstructor;
  4. /**
  5. * @author 许大仙
  6. * @version 1.0
  7. * @since 2022-01-04 14:02
  8. */
  9. @RequiredArgsConstructor
  10. public class Emp {
  11. private final String age;
  12. @NonNull
  13. private String empNo;
  14. @NonNull
  15. private String empName;
  16. private Double salary;
  17. }
  • 通过 IDEA 查看反编译生成的 class 文件,目录为 build/classes :
  1. //
  2. // Source code recreated from a .class file by IntelliJ IDEA
  3. // (powered by FernFlower decompiler)
  4. //
  5. package com.github.fairy.era.domain;
  6. import lombok.NonNull;
  7. public class Emp {
  8. private final String age;
  9. @NonNull
  10. private String empNo;
  11. @NonNull
  12. private String empName;
  13. private Double salary;
  14. public Emp(final String age, @NonNull final String empNo, @NonNull final String empName) {
  15. if (empNo == null) {
  16. throw new NullPointerException("empNo is marked non-null but is null");
  17. } else if (empName == null) {
  18. throw new NullPointerException("empName is marked non-null but is null");
  19. } else {
  20. this.age = age;
  21. this.empNo = empNo;
  22. this.empName = empName;
  23. }
  24. }
  25. }

5.4.6 microboot-web 子模块(@AllArgsConstructor 注解)

  • 会为所有的属性生成构造方法,不管此属性是否是 @NonNull 注解或 final 关键字修饰。
  1. @AllArgsConstructor
  2. public class Emp {
  3. private final String age;
  4. @NonNull
  5. private String empNo;
  6. @NonNull
  7. private String empName;
  8. private Double salary;
  9. }
  • 通过 IDEA 查看反编译生成的 class 文件,目录为 build/classes :
  1. //
  2. // Source code recreated from a .class file by IntelliJ IDEA
  3. // (powered by FernFlower decompiler)
  4. //
  5. package com.github.fairy.era.domain;
  6. import lombok.NonNull;
  7. public class Emp {
  8. private final String age;
  9. @NonNull
  10. private String empNo;
  11. @NonNull
  12. private String empName;
  13. private Double salary;
  14. public Emp(String age, @NonNull String empNo, @NonNull String empName, Double salary) {
  15. if (empNo == null) {
  16. throw new NullPointerException("empNo is marked non-null but is null");
  17. } else if (empName == null) {
  18. throw new NullPointerException("empName is marked non-null but is null");
  19. } else {
  20. this.age = age;
  21. this.empNo = empNo;
  22. this.empName = empName;
  23. this.salary = salary;
  24. }
  25. }
  26. }

5.5 Accessor(访问器模式)

5.5.1 概述

  • 虽然 Lombok 最为常用的是生成基本的类结构(@Data 注解是最为常用的一个),但是在 Lombok 设计的时候也充分的考虑到了各种设计模式的需求,所以对于属性的访问就存在了访问器模式,同时对于访问器操作形式提供了三种不同的方案:fluent、chain、prefix。

5.5.2 microboot-web 子模块(fluent 模式)

  • fluent 模式的特点在于直接将属性名称作为属性设置和返回的方法名称(基于方法的重载来进行处理),随后可以在进行属性配置的时候直接使用代码链的方法来实现相关属性的设置。
  • 在 Message 类中采用访问器模式,随后基于 fluent 操作形式定义:
  1. package com.github.fairy.era.domain;
  2. import lombok.Data;
  3. import lombok.experimental.Accessors;
  4. import java.util.Date;
  5. /**
  6. * @author 许大仙
  7. * @version 1.0
  8. * @since 2022-01-04 13:35
  9. */
  10. @Data
  11. @Accessors(fluent = true)
  12. public class Message {
  13. private String title;
  14. private Date publishDate;
  15. private String content;
  16. }
  • 通过 IDEA 查看反编译生成的 class 文件,目录为 build/classes :
  1. //
  2. // Source code recreated from a .class file by IntelliJ IDEA
  3. // (powered by FernFlower decompiler)
  4. //
  5. package com.github.fairy.era.domain;
  6. import java.util.Date;
  7. public class Message {
  8. private String title;
  9. private Date publishDate;
  10. private String content;
  11. public Message() {
  12. }
  13. public String title() { // 属性获取方法使用的是属性名称进行配置
  14. return this.title;
  15. }
  16. public Date publishDate() {
  17. return this.publishDate;
  18. }
  19. public String content() {
  20. return this.content;
  21. }
  22. public Message title(String title) { // 属性设置方法使用的是属性名称进行配置
  23. this.title = title;
  24. return this;
  25. }
  26. public Message publishDate(Date publishDate) {
  27. this.publishDate = publishDate;
  28. return this;
  29. }
  30. public Message content(String content) {
  31. this.content = content;
  32. return this;
  33. }
  34. public boolean equals(Object o) {
  35. if (o == this) {
  36. return true;
  37. } else if (!(o instanceof Message)) {
  38. return false;
  39. } else {
  40. Message other = (Message)o;
  41. if (!other.canEqual(this)) {
  42. return false;
  43. } else {
  44. label47: {
  45. Object this$title = this.title();
  46. Object other$title = other.title();
  47. if (this$title == null) {
  48. if (other$title == null) {
  49. break label47;
  50. }
  51. } else if (this$title.equals(other$title)) {
  52. break label47;
  53. }
  54. return false;
  55. }
  56. Object this$publishDate = this.publishDate();
  57. Object other$publishDate = other.publishDate();
  58. if (this$publishDate == null) {
  59. if (other$publishDate != null) {
  60. return false;
  61. }
  62. } else if (!this$publishDate.equals(other$publishDate)) {
  63. return false;
  64. }
  65. Object this$content = this.content();
  66. Object other$content = other.content();
  67. if (this$content == null) {
  68. if (other$content != null) {
  69. return false;
  70. }
  71. } else if (!this$content.equals(other$content)) {
  72. return false;
  73. }
  74. return true;
  75. }
  76. }
  77. }
  78. protected boolean canEqual(Object other) {
  79. return other instanceof Message;
  80. }
  81. public int hashCode() {
  82. int PRIME = true;
  83. int result = 1;
  84. Object $title = this.title();
  85. int result = result * 59 + ($title == null ? 43 : $title.hashCode());
  86. Object $publishDate = this.publishDate();
  87. result = result * 59 + ($publishDate == null ? 43 : $publishDate.hashCode());
  88. Object $content = this.content();
  89. result = result * 59 + ($content == null ? 43 : $content.hashCode());
  90. return result;
  91. }
  92. public String toString() {
  93. return "Message(title=" + this.title() + ", publishDate=" + this.publishDate() + ", content=" + this.content() + ")";
  94. }
  95. }
  • 测试:
  1. package com.github.fairy.era;
  2. import com.github.fairy.era.domain.Message;
  3. import org.junit.jupiter.api.Test;
  4. import org.springframework.boot.test.context.SpringBootTest;
  5. import java.util.Date;
  6. /**
  7. * @author 许大仙
  8. * @version 1.0
  9. * @since 2022-01-04 09:36
  10. */
  11. @SpringBootTest
  12. public class ApplicationTest {
  13. @Test
  14. public void test() {
  15. Message message = new Message();
  16. message.title("许大仙").publishDate(new Date()).content("你大爷的");
  17. System.out.println("message = " + message);
  18. }
  19. }
  • 测试结果:
  1. message = Message(title=许大仙, publishDate=Tue Jan 04 15:26:24 CST 2022, content=你大爷的)
  • 在进行一个开发框架处理的时候(Mybatis、SpringDataJPA),都要求通过 setter 方法进行设置,以及在输出的时候要求通过 getter 方法获取内容,这样一来就无法满足正常的开发设计要求了。
  • 但是对于一个独立的程序类来说,此时的功能还是比较强大的,因为有了更加简单的属性设置模式。

5.5.3 microboot-web 子模块(chain 模式)

  • chain 模式的特点在于每个 setter 方法都返回当前对象的实例,这样就可以基于代码链的方式来进行设置处理了。
  • 在 Message 类中采用访问器模式,随后基于 chain 操作形式定义:
  1. package com.github.fairy.era.domain;
  2. import lombok.Data;
  3. import lombok.experimental.Accessors;
  4. import java.util.Date;
  5. /**
  6. * @author 许大仙
  7. * @version 1.0
  8. * @since 2022-01-04 13:35
  9. */
  10. @Data
  11. @Accessors(chain = true)
  12. public class Message {
  13. private String title;
  14. private Date publishDate;
  15. private String content;
  16. }
  • 通过 IDEA 查看反编译生成的 class 文件,目录为 build/classes :
  1. //
  2. // Source code recreated from a .class file by IntelliJ IDEA
  3. // (powered by FernFlower decompiler)
  4. //
  5. package com.github.fairy.era.domain;
  6. import java.util.Date;
  7. public class Message {
  8. private String title;
  9. private Date publishDate;
  10. private String content;
  11. public Message() {
  12. }
  13. public String getTitle() {
  14. return this.title;
  15. }
  16. public Date getPublishDate() {
  17. return this.publishDate;
  18. }
  19. public String getContent() {
  20. return this.content;
  21. }
  22. public Message setTitle(final String title) { // setter 方法的返回值不是 void
  23. this.title = title;
  24. return this;
  25. }
  26. public Message setPublishDate(final Date publishDate) {
  27. this.publishDate = publishDate;
  28. return this;
  29. }
  30. public Message setContent(final String content) {
  31. this.content = content;
  32. return this;
  33. }
  34. public boolean equals(final Object o) {
  35. if (o == this) {
  36. return true;
  37. } else if (!(o instanceof Message)) {
  38. return false;
  39. } else {
  40. Message other = (Message)o;
  41. if (!other.canEqual(this)) {
  42. return false;
  43. } else {
  44. label47: {
  45. Object this$title = this.getTitle();
  46. Object other$title = other.getTitle();
  47. if (this$title == null) {
  48. if (other$title == null) {
  49. break label47;
  50. }
  51. } else if (this$title.equals(other$title)) {
  52. break label47;
  53. }
  54. return false;
  55. }
  56. Object this$publishDate = this.getPublishDate();
  57. Object other$publishDate = other.getPublishDate();
  58. if (this$publishDate == null) {
  59. if (other$publishDate != null) {
  60. return false;
  61. }
  62. } else if (!this$publishDate.equals(other$publishDate)) {
  63. return false;
  64. }
  65. Object this$content = this.getContent();
  66. Object other$content = other.getContent();
  67. if (this$content == null) {
  68. if (other$content != null) {
  69. return false;
  70. }
  71. } else if (!this$content.equals(other$content)) {
  72. return false;
  73. }
  74. return true;
  75. }
  76. }
  77. }
  78. protected boolean canEqual(final Object other) {
  79. return other instanceof Message;
  80. }
  81. public int hashCode() {
  82. int PRIME = true;
  83. int result = 1;
  84. Object $title = this.getTitle();
  85. int result = result * 59 + ($title == null ? 43 : $title.hashCode());
  86. Object $publishDate = this.getPublishDate();
  87. result = result * 59 + ($publishDate == null ? 43 : $publishDate.hashCode());
  88. Object $content = this.getContent();
  89. result = result * 59 + ($content == null ? 43 : $content.hashCode());
  90. return result;
  91. }
  92. public String toString() {
  93. return "Message(title=" + this.getTitle() + ", publishDate=" + this.getPublishDate() + ", content=" + this.getContent() + ")";
  94. }
  95. }
  • 测试:
  1. package com.github.fairy.era;
  2. import com.github.fairy.era.domain.Message;
  3. import org.junit.jupiter.api.Test;
  4. import org.springframework.boot.test.context.SpringBootTest;
  5. import java.util.Date;
  6. /**
  7. * @author 许大仙
  8. * @version 1.0
  9. * @since 2022-01-04 09:36
  10. */
  11. @SpringBootTest
  12. public class ApplicationTest {
  13. @Test
  14. public void test() {
  15. Message message = new Message();
  16. message.setTitle("许大仙").setPublishDate(new Date()).setContent("你大爷的");
  17. System.out.println("message = " + message);
  18. }
  19. }
  • 测试结果:
  1. message = Message(title=许大仙, publishDate=Tue Jan 04 15:38:03 CST 2022, content=你大爷的)
  • 在大部分基于反射的模式来获取 setter 方法对象都是采用 void 返回值类型来进行获取的,所以即便此时有了返回值,对于框架来说也无法正常的采用代码链来处理,但是,对于我们手动设置属性来说是很方便的。

5.5.4 microboot-web 子模块(prefix 模式)

  • 如果习惯于给属性定义前缀,但是又想在生成 setter 和 getter 的时候不带有前缀,那么就可以使用 refix 模式 了。
  • 在 Message 类中采用访问器模式,随后基于 prefix 操作形式定义:
  1. package com.github.fairy.era.domain;
  2. import lombok.Data;
  3. import lombok.experimental.Accessors;
  4. import java.util.Date;
  5. /**
  6. * @author 许大仙
  7. * @version 1.0
  8. * @since 2022-01-04 13:35
  9. */
  10. @Data
  11. @Accessors(prefix = "spring")
  12. public class Message {
  13. private String springTitle;
  14. private Date springPublishDate;
  15. private String springContent;
  16. }
  • 通过 IDEA 查看反编译生成的 class 文件,目录为 build/classes :
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.github.fairy.era.domain;

import java.util.Date;

public class Message {
    private String springTitle;
    private Date springPublishDate;
    private String springContent;

    public Message() {
    }

    public String getTitle() {
        return this.springTitle;
    }

    public Date getPublishDate() {
        return this.springPublishDate;
    }

    public String getContent() {
        return this.springContent;
    }

    public void setTitle(String springTitle) {
        this.springTitle = springTitle;
    }

    public void setPublishDate(Date springPublishDate) {
        this.springPublishDate = springPublishDate;
    }

    public void setContent(String springContent) {
        this.springContent = springContent;
    }

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof Message)) {
            return false;
        } else {
            Message other = (Message)o;
            if (!other.canEqual(this)) {
                return false;
            } else {
                label47: {
                    Object this$springTitle = this.getTitle();
                    Object other$springTitle = other.getTitle();
                    if (this$springTitle == null) {
                        if (other$springTitle == null) {
                            break label47;
                        }
                    } else if (this$springTitle.equals(other$springTitle)) {
                        break label47;
                    }

                    return false;
                }

                Object this$springPublishDate = this.getPublishDate();
                Object other$springPublishDate = other.getPublishDate();
                if (this$springPublishDate == null) {
                    if (other$springPublishDate != null) {
                        return false;
                    }
                } else if (!this$springPublishDate.equals(other$springPublishDate)) {
                    return false;
                }

                Object this$springContent = this.getContent();
                Object other$springContent = other.getContent();
                if (this$springContent == null) {
                    if (other$springContent != null) {
                        return false;
                    }
                } else if (!this$springContent.equals(other$springContent)) {
                    return false;
                }

                return true;
            }
        }
    }

    protected boolean canEqual(Object other) {
        return other instanceof Message;
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        Object $springTitle = this.getTitle();
        int result = result * 59 + ($springTitle == null ? 43 : $springTitle.hashCode());
        Object $springPublishDate = this.getPublishDate();
        result = result * 59 + ($springPublishDate == null ? 43 : $springPublishDate.hashCode());
        Object $springContent = this.getContent();
        result = result * 59 + ($springContent == null ? 43 : $springContent.hashCode());
        return result;
    }

    public String toString() {
        return "Message(springTitle=" + this.getTitle() + ", springPublishDate=" + this.getPublishDate() + ", springContent=" + this.getContent() + ")";
    }
}
  • 测试:
package com.github.fairy.era;

import com.github.fairy.era.domain.Message;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;

/**
 * @author 许大仙
 * @version 1.0
 * @since 2022-01-04 09:36
 */
@SpringBootTest
public class ApplicationTest {

    @Test
    public void test() {
        Message message = new Message();
        message.setTitle("许大仙");
        message.setPublishDate(new Date());
        message.setContent("你大爷的");
        System.out.println("message = " + message);
    }
}
  • 测试结果:
message = Message(springTitle=许大仙, springPublishDate=Tue Jan 04 15:55:37 CST 2022, springContent=你大爷的)

5.4 builder(构造者模式)

5.4.1 概述

  • 传统的简单 Java 类如果要想进行属性的设置,肯定需要下进行对象的实例化,随后利用一系列的 setter 方法设置属性;当然,也可以基于 Accessor 模式采用代码链的形式进行处理。
  • 在 Java 里面还存在一种构造者模式,可以直接利用其内部所提供的一个方法实现对象的完整构建。

5.4.2 microboot-web 子模块

  • 采用 @Builder 注解进行配置。
package com.github.fairy.era.domain;

import lombok.Builder;

import java.util.Date;

/**
 * @author 许大仙
 * @version 1.0
 * @since 2022-01-04 13:35
 */
@Builder
public class Message {

    private String title;

    private Date publishDate;

    private String content;

}
  • 通过 IDEA 查看反编译生成的 class 文件,目录为 build/classes :
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.github.fairy.era.domain;

import java.util.Date;

public class Message {
    private String title;
    private Date publishDate;
    private String content;

    Message(String title, Date publishDate, String content) {
        this.title = title;
        this.publishDate = publishDate;
        this.content = content;
    }

    public static Message.MessageBuilder builder() {
        return new Message.MessageBuilder();
    }

    public static class MessageBuilder { // 用来帮助开发者创建 Message 实例
        private String title;
        private Date publishDate;
        private String content;

        MessageBuilder() {
        }

        public Message.MessageBuilder title(String title) {
            this.title = title;
            return this;
        }

        public Message.MessageBuilder publishDate(Date publishDate) {
            this.publishDate = publishDate;
            return this;
        }

        public Message.MessageBuilder content(String content) {
            this.content = content;
            return this;
        }

        public Message build() {
            return new Message(this.title, this.publishDate, this.content);
        }

        public String toString() {
            return "Message.MessageBuilder(title=" + this.title + ", publishDate=" + this.publishDate + ", content=" + this.content + ")";
        }
    }
}
  • 测试:
package com.github.fairy.era;

import com.github.fairy.era.domain.Message;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;

/**
 * @author 许大仙
 * @version 1.0
 * @since 2022-01-04 09:36
 */
@SpringBootTest
public class ApplicationTest {

    @Test
    public void test() {
        Message message = Message.builder().title("许大仙").publishDate(new Date()).content("你大爷").build();
        System.out.println("message = " + message);
    }
}
  • 此时 Message 类如果加上 @Data 注解依然会提供 setter 和 getter 方法,和其他开发框架的整合不会成为问题,强烈推荐

5.5 异常处理

5.5.1 概述

  • 在 Java 编程里面最强大的部分莫过于异常处理机制了,但是每次编写代码的时候都需要自己手动输入 try…catch..finally 之类的,实现是太繁琐了。
  • 原始的异常处理:
package com.github.fairy.era.lombok;

/**
 * @author 许大仙
 * @version 1.0
 * @since 2022-01-04 16:26
 */
public class MessageHandler {

    public static void print(String msg) {// 信息输出
        if (null == msg) { // 内容为空
            try {
                throw new Exception("传递的 msg 参数为空");
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        System.out.println("msg = " + msg);
    }
}
  • Lombok 为了解决此类的异常处理的繁琐代码定义,提供了一个专门处理异常的@SneakyThrows 注解 ,帮助用户自动的进行异常捕获。

5.5.2 microboot-web 子模块

  • 使用 @SneakyThrows 注解处理异常。
package com.github.fairy.era.lombok;

import lombok.SneakyThrows;

/**
 * @author 许大仙
 * @version 1.0
 * @since 2022-01-04 16:26
 */
public class MessageHandler {

    @SneakyThrows // 会自动的生成 try...catch
    public static void print(String msg) {// 信息输出
        if (null == msg) {
            throw new Exception("传递的 msg 参数为空");
        }

        System.out.println("msg = " + msg);
    }
}
  • 通过 IDEA 查看反编译生成的 class 文件,目录为 build/classes :
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.github.fairy.era.lombok;

public class MessageHandler {
    public MessageHandler() {
    }

    public static void print(String msg) {
        try {
            if (null == msg) {
                throw new Exception("传递的 msg 参数为空");
            } else {
                System.out.println("msg = " + msg);
            }
        } catch (Throwable var2) {
            throw var2;
        }
    }
}
  • 此时就可以直接发现,对于当前的代码会自动的帮助用户进行整个的 try..catch 处理,同时会将捕获的异常继续向上抛。

5.6 IO 流自动关闭

5.6.1 概述

  • IO 流是属于资源操作的,操作完之后一定需要进行资源的释放,但是传统的资源释放都是手动的形式完成的,例如:可以在 try 之中实例化 IO 流对象,随后基于 AutoCloseable 实现自动关闭,但是在 Lombok 里面,提供了 @Cleanup 注解使得这一切的操作又得到了极大的简化,可以帮助用户自动关闭 IO 流处理。

5.6.2 microboot-web 子模块

  • 定义一个数据读取类,并使用 @Cleanup 帮助我们自动关闭 IO 流。
package com.github.fairy.era.lombok;

import lombok.Cleanup;
import lombok.Data;
import lombok.NonNull;
import lombok.SneakyThrows;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author 许大仙
 * @version 1.0
 * @since 2022-01-04 16:26
 */
@Data
public class MessageReader {

    /**
     * 文件路径
     */
    @NonNull
    private String filePath;

    /**
     * 文件名称
     */
    @NonNull
    private String fileName;

    /**
     * 数据读取
     *
     * @return
     */
    @SneakyThrows
    public String read() {
        StringBuilder sb = new StringBuilder();
        @Cleanup InputStream is = new FileInputStream(new File(this.filePath, this.fileName));
        @Cleanup BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
        String readLine = reader.readLine();
        if (null != readLine) {
            sb.append(readLine);
        }
        return sb.toString();
    }
}
  • 通过 IDEA 查看反编译生成的 class 文件,目录为 build/classes :
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.github.fairy.era.lombok;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import lombok.NonNull;

public class MessageReader {
    @NonNull
    private String filePath;
    @NonNull
    private String fileName;

    public String read() {
        try {
            StringBuilder sb = new StringBuilder();
            FileInputStream is = new FileInputStream(new File(this.filePath, this.fileName));

            String var5;
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));

                try {
                    String readLine = reader.readLine();
                    if (null != readLine) {
                        sb.append(readLine);
                    }

                    var5 = sb.toString();
                } finally {
                    if (Collections.singletonList(reader).get(0) != null) {
                        reader.close();
                    }

                }
            } finally {
                if (Collections.singletonList(is).get(0) != null) {
                    is.close();
                }

            }

            return var5;
        } catch (Throwable var16) {
            throw var16;
        }
    }

    public MessageReader(@NonNull String filePath, @NonNull String fileName) {
        if (filePath == null) {
            throw new NullPointerException("filePath is marked non-null but is null");
        } else if (fileName == null) {
            throw new NullPointerException("fileName is marked non-null but is null");
        } else {
            this.filePath = filePath;
            this.fileName = fileName;
        }
    }

    @NonNull
    public String getFilePath() {
        return this.filePath;
    }

    @NonNull
    public String getFileName() {
        return this.fileName;
    }

    public void setFilePath(@NonNull String filePath) {
        if (filePath == null) {
            throw new NullPointerException("filePath is marked non-null but is null");
        } else {
            this.filePath = filePath;
        }
    }

    public void setFileName(@NonNull String fileName) {
        if (fileName == null) {
            throw new NullPointerException("fileName is marked non-null but is null");
        } else {
            this.fileName = fileName;
        }
    }

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof MessageReader)) {
            return false;
        } else {
            MessageReader other = (MessageReader)o;
            if (!other.canEqual(this)) {
                return false;
            } else {
                Object this$filePath = this.getFilePath();
                Object other$filePath = other.getFilePath();
                if (this$filePath == null) {
                    if (other$filePath != null) {
                        return false;
                    }
                } else if (!this$filePath.equals(other$filePath)) {
                    return false;
                }

                Object this$fileName = this.getFileName();
                Object other$fileName = other.getFileName();
                if (this$fileName == null) {
                    if (other$fileName != null) {
                        return false;
                    }
                } else if (!this$fileName.equals(other$fileName)) {
                    return false;
                }

                return true;
            }
        }
    }

    protected boolean canEqual(Object other) {
        return other instanceof MessageReader;
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        Object $filePath = this.getFilePath();
        int result = result * 59 + ($filePath == null ? 43 : $filePath.hashCode());
        Object $fileName = this.getFileName();
        result = result * 59 + ($fileName == null ? 43 : $fileName.hashCode());
        return result;
    }

    public String toString() {
        return "MessageReader(filePath=" + this.getFilePath() + ", fileName=" + this.getFileName() + ")";
    }
}
  • 在以后的项目开发中进行数据库开发、文件开发、网络开发等,就不需要再去费劲心思的进行 close() 方法的调用了,直接交给 Lombok 的 @Cleanup 注解即可。

5.7 同步方法

5.7.1 概述

  • 要进行多线程的售票处理,就需要进行同步的操作,可以通过 Lombok 提供的 @Synchronized 注解轻松处理。

5.7.2 microboot-web 子模块

  • 创建一个售票的程序类:
package com.github.fairy.era.lombok;

import lombok.SneakyThrows;
import lombok.Synchronized;

import java.util.concurrent.TimeUnit;

/**
 * @author 许大仙
 * @version 1.0
 * @since 2022-01-04 17:13
 */
public class SellTickets implements Runnable {

    private int tickets = 100;

    @Synchronized
    @SneakyThrows
    @Override
    public void run() {
        while (true) {
            if (this.tickets > 0) {
                TimeUnit.SECONDS.sleep(1); // 模拟延迟
                System.out.println(Thread.currentThread().getName() + ":售第" + this.tickets-- + "张票");
            }
        }
    }
}
  • 通过 IDEA 查看反编译生成的 class 文件,目录为 build/classes :
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.github.fairy.era.lombok;

import java.util.concurrent.TimeUnit;

public class SellTickets implements Runnable {
    private final Object $lock = new Object[0];
    private int tickets = 100;

    public SellTickets() {
    }

    public void run() {
        try {
            synchronized(this.$lock){}

            try {
                while(true) {
                    while(this.tickets <= 0) {
                    }

                    TimeUnit.SECONDS.sleep(1L);
                    System.out.println(Thread.currentThread().getName() + ":售第" + this.tickets-- + "张票");
                }
            } finally {
                ;
            }
        } catch (Throwable var6) {
            throw var6;
        }
    }
}
  • 测试:
package com.github.fairy.era;

import com.github.fairy.era.lombok.SellTickets;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @author 许大仙
 * @version 1.0
 * @since 2022-01-04 09:36
 */
@SpringBootTest
public class ApplicationTest {

    public static void main(String[] args) {
        SellTickets sellTickets = new SellTickets();
        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(sellTickets, "窗口" + i);
            t.start();
        }
    }

}
  • 在实际的项目开发过程之中,对于多线程的同步处理绝对没有这么简单,毕竟还有一个最为庞大的 juc 的组件包,这个组件包里面还需要考虑 AQS、CAS 的设计问题,以上的同步仅仅实现了一个最为基础的同步,同时这个同步也存在有死锁的安全隐患,所以在使用的时候请慎用。