当前位置:   article > 正文

2021最新版SpringBoot 速记

spring.datasource.maxactive最新

点击上方蓝色字体,选择“标星公众号”

优质文章,第一时间送达

关注公众号后台回复paymall获取实战项目资料+视频

作者:JingQ

来源:http://r6d.cn/X6FP

下面是简单的速记,根据使用场景可以快速定位到知识点:

Demo 脚手架项目地址:

https://github.com/Vip-Augus/springboot-note

Table of Contents generated with DocToc

  • SpringBoot 速记

    • 一、引入依赖

    • 二、配置 Swagger 参数

    • 一、引入依赖

    • 二、配置邮箱的参数

    • 三、写模板和发送内容

    • 一、引用 Redis 依赖

    • 二、参数配置

    • 三、代码使用

    • 一、添加 mybatis 和 druid 依赖

    • 二、配置数据库和连接池参数

    • 三、其他 mybatis 配置

    • @ExceptionHandler 错误处理

    • @ModelAttribute 视图属性

    • 常规配置

    • HTTPS 配置

    • 构建项目

    • SpringBoot 基础配置

    • Spring Boot Starters

    • @SpringBootApplication

    • Web 容器配置

    • @ConfigurationProperties

    • Profile

    • @ControllerAdvice 用来处理全局数据

    • CORS 支持,跨域资源共享

    • 注册 MVC 拦截器

    • 开启 AOP 切面控制

    • 整合 Mybatis 和 Druid

    • 整合 Redis

    • 发送 HTML 样式的邮件

    • 整合 Swagger (API 文档)

    • 总结

    • 参考资料

构建项目

相比于使用 IDEA 的模板创建项目,我更推荐的是在 Spring 官网上选择参数一步生成项目

https://start.spring.io/

我们只需要做的事情,就是修改组织名和项目名,点击 Generate the project,下载到本地,然后使用 IDEA 打开

这个时候,不需要任何配置,点击 Application 类的 run 方法就能直接启动项目。


SpringBoot 基础配置

Spring Boot Starters

引用自参考资料 1 描述:

starter的理念:starter 会把所有用到的依赖都给包含进来,避免了开发者自己去引入依赖所带来的麻烦。需要注意的是不同的 starter 是为了解决不同的依赖,所以它们内部的实现可能会有很大的差异,例如 jpa 的 starter 和 Redis 的 starter 可能实现就不一样,这是因为 starter 的本质在于 synthesize,这是一层在逻辑层面的抽象,也许这种理念有点类似于 Docker,因为它们都是在做一个“包装”的操作,如果你知道 Docker 是为了解决什么问题的,也许你可以用 Docker 和 starter 做一个类比。

我们知道在 SpringBoot 中很重要的一个概念就是,「约定优于配置」,通过特定方式的配置,可以减少很多步骤来实现想要的功能。

例如如果我们想要使用缓存 Redis

在之前的可能需要通过以下几个步骤:

  1. 在 pom 文件引入特定版本的 redis

  2. 在 .properties 文件中配置参数

  3. 根据参数,新建一个又一个 jedis 连接

  4. 定义一个工具类,手动创建连接池来管理

经历了上面的步骤,我们才能正式使用 Redis

但在 Spring Boot 中,一切因为 Starter 变得简单

  1. 在 pom 文件中引入 spring-boot-starter-data-redis

  2. 在 .properties 文件中配置参数

通过上面两个步骤,配置自动生效,具体生效的 bean 是 RedisAutoConfiguration,自动配置类的名字都有一个特点,叫做 xxxAutoConfiguration

可以来简单看下这个类:

  1. @Configuration
  2. @ConditionalOnClass(RedisOperations.class)
  3. @EnableConfigurationProperties(RedisProperties.class)
  4. @Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
  5. public class RedisAutoConfiguration {
  6.  @Bean
  7.  @ConditionalOnMissingBean(name = "redisTemplate")
  8.  public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
  9.    throws UnknownHostException {
  10.   RedisTemplate<Object, Object> template = new RedisTemplate<>();
  11.   template.setConnectionFactory(redisConnectionFactory);
  12.   return template;
  13.  }
  14.  @Bean
  15.  @ConditionalOnMissingBean
  16.  public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)
  17.    throws UnknownHostException {
  18.   StringRedisTemplate template = new StringRedisTemplate();
  19.   template.setConnectionFactory(redisConnectionFactory);
  20.   return template;
  21.  }
  22. }
  23. @ConfigurationProperties(prefix = "spring.redis")
  24. public class RedisProperties {...}

可以看到,Redis 自动配置类,读取了以 spring.redis 为前缀的配置,然后加载 redisTemplate 到容器中,然后我们在应用中就能使用 RedisTemplate 来对缓存进行操作~(还有很多细节没有细说,例如 @ConditionalOnMissingBean 先留个坑(●´∀`●)ノ)

  1. @Autowired
  2. private RedisTemplate redisTemplate;
  3. ValueOperations ops2 = redisTemplate.opsForValue();
  4. Book book = (Book) ops2.get("b1");

@SpringBootApplication

该注解是加载项目的启动类上的,而且它是一个组合注解:

  1. @SpringBootConfiguration
  2. @EnableAutoConfiguration
  3. @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
  4.   @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
  5. public @interface SpringBootApplication {...}

下面是这三个核心注解的解释:

注解名解释
@SpringBootConfiguration表明这是一个配置类,开发者可以在这个类中配置 Bean
@EnableAutoConfiguration表示开启自动化配置
@ComponentScan完成包扫描,默认扫描的类位于当前类所在包的下面

通过该注解,我们执行 mian 方法:

SpringApplication.run(SpringBootLearnApplication.class, args);

就可以启动一个 SpringApplicaiton 应用了。


Web 容器配置

常规配置

配置名解释
server.port=8081配置了容器的端口号,默认是 8080
server.error.path=/error配置了项目出错时跳转的页面
server.servlet.session.timeout=30msession 失效时间,m 表示分钟,如果不写单位,默认是秒 s
server.servlet.context-path=/项目名称,不配置时默认为/。配置后,访问时需加上前缀
server.tomcat.uri-encoding=utf-8Tomcat 请求编码格式
server.tomcat.max-threads=500Tomcat 最大线程数
server.tomcat.basedir=/home/tmpTomcat 运行日志和临时文件的目录,如不配置,默认使用系统的临时目录

HTTPS 配置

配置名解释
server.ssl.key-store=xxx秘钥文件名
server.ssl.key-alias=xxx秘钥别名
server.ssl.key-store-password=123456秘钥密码

想要详细了解如何配置 HTTPS,可以参考这篇文章 Spring Boot 使用SSL-HTTPS


@ConfigurationProperties

这个注解可以放在类上或者 @Bean 注解所在方法上,这样 SpringBoot 就能够从配置文件中,读取特定前缀的配置,将属性值注入到对应的属性。

使用例子:

  1. @Configuration
  2. @ConfigurationProperties(prefix = "spring.datasource")
  3. public class DruidConfigBean {
  4.     private Integer initialSize;
  5.     private Integer minIdle;
  6.     private Integer maxActive;
  7.     
  8.     private List<String> customs;
  9.     
  10.     ...
  11. }
  12. application.properties
  13. spring.datasource.initialSize=5
  14. spring.datasource.minIdle=5
  15. spring.datasource.maxActive=20
  16. spring.datasource.customs=test1,test2,test3

其中,如果对象是列表结构,可以在配置文件中使用 , 逗号进行分割,然后注入到相应的属性中。


Profile

使用该属性,可以快速切换配置文件,在 SpringBoot 默认约定中,不同环境下配置文件名称规则为 application-{profile}.propertieprofile 占位符表示当前环境的名称。

1、配置 application.properties

spring.profiles.active=dev

2、在代码中配置 在启动类的 main 方法上添加 setAdditionalProfiles("{profile}");

  1. SpringApplicationBuilder builder = new SpringApplicationBuilder(SpringBootLearnApplication.class);
  2. builder.application().setAdditionalProfiles("prod");
  3. builder.run(args);

3、启动参数配置

java -jar demo.jar --spring.active.profile=dev

@ControllerAdvice 用来处理全局数据

@ControllerAdvice 是 @Controller 的增强版。主要用来处理全局数据,一般搭配 @ExceptionHandler 、@ModelAttribute 以及 @InitBinder 使用。

@ExceptionHandler 错误处理

  1. /**
  2.  * 加强版控制器,拦截自定义的异常处理
  3.  *
  4.  */
  5. @ControllerAdvice
  6. public class CustomExceptionHandler {
  7.     
  8.     // 指定全局拦截的异常类型,统一处理
  9.     @ExceptionHandler(MaxUploadSizeExceededException.class)
  10.     public void uploadException(MaxUploadSizeExceededException e, HttpServletResponse response) throws IOException {
  11.         response.setContentType("text/html;charset=utf-8");
  12.         PrintWriter out = response.getWriter();
  13.         out.write("上传文件大小超出限制");
  14.         out.flush();
  15.         out.close();
  16.     }
  17. }

@ModelAttribute 视图属性

  1. @ControllerAdvice
  2. public class CustomModelAttribute {
  3.     
  4.     // 
  5.     @ModelAttribute(value = "info")
  6.     public Map<String, String> userInfo() throws IOException {
  7.         Map<String, String> map = new HashMap<>();
  8.         map.put("test""testInfo");
  9.         return map;
  10.     }
  11. }
  12. @GetMapping("/hello")
  13. public String hello(Model model) {
  14.     Map<String, Object> map = model.asMap();
  15.     Map<String, String> infoMap = (Map<String, String>) map.get("info");
  16.     return infoMap.get("test");
  17. }
  • key : @ModelAttribute 注解中的 value 属性

  • 使用场景:任何请求 controller 类,通过方法参数中的 Model 都可以获取 value 对应的属性


CORS 支持,跨域资源共享

CORS(Cross-Origin Resource Sharing),跨域资源共享技术,目的是为了解决前端的跨域请求。

引用:当一个资源从与该资源本身所在服务器不同的域或端口请求一个资源时,资源会发起一个跨域HTTP请求

详细可以参考这篇文章-springboot系列文章之实现跨域请求(CORS),这里只是记录一下如何使用:

例如在我的前后端分离 demo 中,如果没有通过 Nginx 转发,那么将会提示如下信息:

Access to fetch at ‘http://localhost:8888/login‘ from origin ‘http://localhost:3000‘ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Credentials’ header in the response is ‘’ which must be ‘true’ when the request’s credentials mode is ‘include’

为了解决这个问题,在前端不修改的情况下,需要后端加上如下两行代码:

  1. // 第一行,支持的域
  2. @CrossOrigin(origins = "http://localhost:3000")
  3. @RequestMapping(value = "/login", method = RequestMethod.GET)
  4. @ResponseBody
  5. public String login(HttpServletResponse response) {
  6.     // 第二行,响应体添加头信息(这一行是解决上面的提示)
  7.     response.setHeader("Access-Control-Allow-Credentials""true");
  8.     return HttpRequestUtils.login();
  9. }

注册 MVC 拦截器

在 MVC 模块中,也提供了类似 AOP 切面管理的扩展,能够拥有更加精细的拦截处理能力。

核心在于该接口:HandlerInterceptor,使用方式如下:

  1. /**
  2.  * 自定义 MVC 拦截器
  3.  */
  4. public class MyInterceptor implements HandlerInterceptor {
  5.     @Override
  6.     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  7.         // 在 controller 方法之前调用
  8.         return true;
  9.     }
  10.     @Override
  11.     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  12.         // 在 controller 方法之后调用
  13.     }
  14.     @Override
  15.     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  16.         // 在 postHandle 方法之后调用
  17.     }
  18. }

注册代码:

  1. /**
  2.  * 全局控制的 mvc 配置
  3.  */
  4. @Configuration
  5. public class MyWebMvcConfig implements WebMvcConfigurer {
  6.     @Override
  7.     public void addInterceptors(InterceptorRegistry registry) {
  8.         registry.addInterceptor(new MyInterceptor())
  9.                 // 表示拦截的 URL
  10.                 .addPathPatterns("/**")
  11.                 // 表示需要排除的路径
  12.                 .excludePathPatterns("/hello");
  13.     }
  14. }

拦截器执行顺序:preHandle -> controller -> postHandle -> afterCompletion,同时需要注意的是,只有 preHandle 方法返回 true,后面的方法才会继续执行。


开启 AOP 切面控制

切面注入是老生常谈的技术,之前学习 Spring 时也有了解,可以参考我之前写过的文章参考一下:

Spring自定义注解实现AOP

Spring 源码学习(八) AOP 使用和实现原理

在 SpringBoot 中,使用起来更加简便,只需要加入该依赖,使用方法与上面一样。

  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-aop</artifactId>
  4. </dependency>

整合 Mybatis 和 Druid

SpringBoot 整合数据库操作,目前主流使用的是 Druid 连接池和 Mybatis 持久层,同样的,starter 提供了简洁的整合方案

项目结构如下:

一、添加 mybatis 和 druid 依赖

  1.  <dependency>
  2.     <groupId>org.mybatis.spring.boot</groupId>
  3.     <artifactId>mybatis-spring-boot-starter</artifactId>
  4.     <version>1.3.2</version>
  5. </dependency>
  6. <dependency>
  7.     <groupId>com.alibaba</groupId>
  8.     <artifactId>druid-spring-boot-starter</artifactId>
  9.     <version>1.1.18</version>
  10. </dependency>

二、配置数据库和连接池参数

  1. # 数据库配置
  2. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  3. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  4. spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
  5. spring.datasource.username=root
  6. spring.datasource.password=12345678
  7. # druid 配置
  8. spring.datasource.druid.initial-size=5
  9. spring.datasource.druid.max-active=20
  10. spring.datasource.druid.min-idle=5
  11. spring.datasource.druid.max-wait=60000
  12. spring.datasource.druid.pool-prepared-statements=true
  13. spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
  14. spring.datasource.druid.max-open-prepared-statements=20
  15. spring.datasource.druid.validation-query=SELECT 1
  16. spring.datasource.druid.validation-query-timeout=30000
  17. spring.datasource.druid.test-on-borrow=true
  18. spring.datasource.druid.test-on-return=false
  19. spring.datasource.druid.test-while-idle=false
  20. #spring.datasource.druid.time-between-eviction-runs-millis=
  21. #spring.datasource.druid.min-evictable-idle-time-millis=
  22. #spring.datasource.druid.max-evictable-idle-time-millis=10000
  23. # Druid stat filter config
  24. spring.datasource.druid.filters=stat,wall
  25. spring.datasource.druid.web-stat-filter.enabled=true
  26. spring.datasource.druid.web-stat-filter.url-pattern=/*
  27. # session 监控
  28. spring.datasource.druid.web-stat-filter.session-stat-enable=true
  29. spring.datasource.druid.web-stat-filter.session-stat-max-count=10
  30. spring.datasource.druid.web-stat-filter.principal-session-name=admin
  31. spring.datasource.druid.web-stat-filter.principal-cookie-name=admin
  32. spring.datasource.druid.web-stat-filter.profile-enable=true
  33. # stat 监控
  34. spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*
  35. spring.datasource.druid.filter.stat.db-type=mysql
  36. spring.datasource.druid.filter.stat.log-slow-sql=true
  37. spring.datasource.druid.filter.stat.slow-sql-millis=1000
  38. spring.datasource.druid.filter.stat.merge-sql=true
  39. spring.datasource.druid.filter.wall.enabled=true
  40. spring.datasource.druid.filter.wall.db-type=mysql
  41. spring.datasource.druid.filter.wall.config.delete-allow=true
  42. spring.datasource.druid.filter.wall.config.drop-table-allow=false
  43. # Druid manage page config
  44. spring.datasource.druid.stat-view-servlet.enabled=true
  45. spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
  46. spring.datasource.druid.stat-view-servlet.reset-enable=true
  47. spring.datasource.druid.stat-view-servlet.login-username=admin
  48. spring.datasource.druid.stat-view-servlet.login-password=admin
  49. #spring.datasource.druid.stat-view-servlet.allow=
  50. #spring.datasource.druid.stat-view-servlet.deny=
  51. spring.datasource.druid.aop-patterns=cn.sevenyuan.demo.*

三、其他 mybatis 配置

本地工程,将 xml 文件放入 resources 资源文件夹下,所以需要加入以下配置,让应用进行识别:

  1.  <build>
  2.     <resources>
  3.         <resource>
  4.             <directory>src/main/resources</directory>
  5.             <includes>
  6.                 <include>**/*</include>
  7.             </includes>
  8.         </resource>
  9.     </resources>
  10.     ...
  11. </build>

通过上面的配置,我本地开启了三个页面的监控:SQL 、 URL 和 Sprint 监控,如下图:

通过上面的配置,SpringBoot 很方便的就整合了 Druid 和 mybatis,同时根据在 properties 文件中配置的参数,开启了 Druid 的监控。

但我根据上面的配置,始终开启不了 session 监控,所以如果需要配置 session 监控或者调整参数具体配置,可以查看官方网站


整合 Redis

我用过 Redis 和 NoSQL,但最熟悉和常用的,还是 Redis ,所以这里记录一下如何整合

一、引用 Redis 依赖

  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-data-redis</artifactId>
  4.     <exclusions>
  5.         <exclusion>
  6.             <artifactId>lettuce-core</artifactId>
  7.             <groupId>io.lettuce</groupId>
  8.         </exclusion>
  9.     </exclusions>
  10. </dependency>
  11. <dependency>
  12.     <groupId>redis.clients</groupId>
  13.     <artifactId>jedis</artifactId>
  14. </dependency>

二、参数配置

  1. # redis 配置
  2. spring.redis.database=0
  3. spring.redis.host=localhost
  4. spring.redis.port=6379
  5. spring.redis.password=
  6. spring.redis.jedis.pool.max-active=8
  7. spring.redis.jedis.pool.max-idle=8
  8. spring.redis.jedis.pool.max-wait=-1ms
  9. spring.redis.jedis.pool.min-idle=0

三、代码使用

  1. @Autowired
  2. private RedisTemplate redisTemplate;
  3. @Autowired
  4. private StringRedisTemplate stringRedisTemplate;
  5. @GetMapping("/testRedis")
  6. public Book getForRedis() {
  7.     ValueOperations<String, String> ops1 = stringRedisTemplate.opsForValue();
  8.     ops1.set("name""Go 语言实战");
  9.     String name = ops1.get("name");
  10.     System.out.println(name);
  11.     ValueOperations ops2 = redisTemplate.opsForValue();
  12.     Book book = (Book) ops2.get("b1");
  13.     if (book == null) {
  14.         book = new Book("Go 语言实战"2"none name", BigDecimal.ONE);
  15.         ops2.set("b1", book);
  16.     }
  17.     return book;
  18. }

这里只是简单记录引用和使用方式,更多功能可以看这里:


发送 HTML 样式的邮件

之前也使用过,所以可以参考这篇文章:

一、引入依赖

  1.  <!-- mail -->
  2. <dependency>
  3.     <groupId>org.springframework.boot</groupId>
  4.     <artifactId>spring-boot-starter-mail</artifactId>
  5. </dependency>
  6. <dependency>
  7.     <groupId>org.springframework.boot</groupId>
  8.     <artifactId>spring-boot-starter-thymeleaf</artifactId>
  9. </dependency>

二、配置邮箱的参数

  1. # mail
  2. spring.mail.host=smtp.qq.com
  3. spring.mail.port=465
  4. spring.mail.username=xxxxxxxx
  5. spring.mail.password=xxxxxxxx
  6. spring.mail.default-encoding=UTF-8
  7. spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
  8. spring.mail.properties.mail.debug=true

如果使用的是 QQ 邮箱,需要在邮箱的设置中获取授权码,填入上面的 password 中

三、写模板和发送内容

  1. MailServiceImpl.java
  2. @Autowired
  3. private JavaMailSender javaMailSender;
  4. @Override
  5. public void sendHtmlMail(String from, String to, String subject, String content) {
  6.     try {
  7.         MimeMessage message = javaMailSender.createMimeMessage();
  8.         MimeMessageHelper helper = new MimeMessageHelper(message, true);
  9.         helper.setFrom(from);
  10.         helper.setTo(to);
  11.         helper.setSubject(subject);
  12.         helper.setText(content, true);
  13.         javaMailSender.send(message);
  14.     } catch (MessagingException e) {
  15.         System.out.println("发送邮件失败");
  16.         log.error("发送邮件失败", e);
  17.     }
  18. }
  19. mailtemplate.html
  20. <!DOCTYPE html>
  21. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  22. <head>
  23.     <meta charset="UTF-8">
  24.     <title>邮件</title>
  25. </head>
  26. <body>
  27. <div th:text="${subject}"></div>
  28. <div>书籍清单
  29.     <table border="1">
  30.         <tr>
  31.             <td>图书编号</td>
  32.             <td>图书名称</td>
  33.             <td>图书作者</td>
  34.         </tr>
  35.         <tr th:each="book:${books}">
  36.             <td th:text="${book.id}"></td>
  37.             <td th:text="${book.name}"></td>
  38.             <td th:text="${book.author}"></td>
  39.         </tr>
  40.     </table>
  41. </div>
  42. </body>
  43. </html>
  44. test.java
  45. @Autowired
  46. private MailService mailService;
  47. @Autowired
  48. private TemplateEngine templateEngine;
  49.     
  50. @Test
  51. public void sendThymeleafMail() {
  52.     Context context = new Context();
  53.     context.setVariable("subject""图书清册");
  54.     List<Book> books = Lists.newArrayList();
  55.     books.add(new Book("Go 语言基础"1"nonename", BigDecimal.TEN));
  56.     books.add(new Book("Go 语言实战"2"nonename", BigDecimal.TEN));
  57.     books.add(new Book("Go 语言进阶"3"nonename", BigDecimal.TEN));
  58.     context.setVariable("books", books);
  59.     String mail = templateEngine.process("mailtemplate.html", context);
  60.     mailService.sendHtmlMail("xxxx@qq.com""xxxxxxxx@qq.com""图书清册", mail);
  61. }

通过上面简单步骤,就能够在代码中发送邮件,例如我们每周要写周报,统计系统运行状态,可以设定定时任务,统计数据,然后自动化发送邮件。


整合 Swagger (API 文档)

一、引入依赖

  1. <!-- swagger -->
  2. <dependency>
  3.     <groupId>io.springfox</groupId>
  4.     <artifactId>springfox-swagger2</artifactId>
  5.     <version>2.9.2</version>
  6. </dependency>
  7. <dependency>
  8.     <groupId>io.springfox</groupId>
  9.     <artifactId>springfox-swagger-ui</artifactId>
  10.     <version>2.9.2</version>
  11. </dependency>

二、配置 Swagger 参数

  1. SwaggerConfig.java
  2. @Configuration
  3. @EnableSwagger2
  4. @EnableWebMvc
  5. public class SwaggerConfig {
  6.     @Bean
  7.     Docket docket() {
  8.         return new Docket(DocumentationType.SWAGGER_2)
  9.                 .select()
  10.                 .apis(RequestHandlerSelectors.basePackage("cn.sevenyuan.demo.controller"))
  11.                 .paths(PathSelectors.any())
  12.                 .build().apiInfo(
  13.                         new ApiInfoBuilder()
  14.                                 .description("Spring Boot learn project")
  15.                                 .contact(new Contact("JingQ""https://github.com/vip-augus""=-=@qq.com"))
  16.                                 .version("v1.0")
  17.                                 .title("API 测试文档")
  18.                                 .license("Apache2.0")
  19.                                 .licenseUrl("http://www.apache.org/licenese/LICENSE-2.0")
  20.                                 .build());
  21.     }
  22. }

设置页面 UI

  1. @Configuration
  2. @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60)
  3. public class MyWebMvcConfig implements WebMvcConfigurer {
  4.     @Override
  5.     public void addResourceHandlers(ResourceHandlerRegistry registry) {
  6.         registry.addResourceHandler("swagger-ui.html")
  7.                 .addResourceLocations("classpath:/META-INF/resources/");
  8.         registry.addResourceHandler("/webjars/**")
  9.                 .addResourceLocations("classpath:/META-INF/resources/webjars/");
  10.     }
  11. }

通过这样就能够识别 @ApiOperation 等接口标志,在网页查看 API 文档,参考文档:Spring Boot实战:集成Swagger2


总结

这边总结的整合经验,只是很基础的配置,在学习的初期,秉着先跑起来,然后不断完善和精进学习。

而且单一整合很容易,但多个依赖会出现想不到的错误,所以在解决环境问题时遇到很多坑,想要使用基础的脚手架,可以尝试跑我上传的项目。

数据库脚本在 resources 目录的 test.sql 文件中

同时,这篇文章中有很多技术没有归纳到,想要深入学习的,请关注松哥的《Spring Boot + Vue 全栈开发》这本书


参考资料

1、Spring Boot Starters

2、Spring Boot 使用SSL-HTTPS

3、Spring Boot(07)——ConfigurationProperties介绍

4、springboot系列文章之实现跨域请求(CORS)

5、Spring Data Redis(一)–解析RedisTemplate

6、Spring Boot实战:集成Swagger2

有热门推荐????

求求你不要手写redis 缓存set,get

肝了一晚上搞出来一个微信订阅号鉴黄机器人

数数FastJson那些年犯下的'血案'...

为什么祖传代码会被称为屎山

面试官:MyBatis的SQL执行流程说这么详细,网上抄的吧!

如何手动获取 Spring 容器中的 Bean?

史上最轻量!阿里强推的新型单元测试工具

腾讯 JDK 正式开源,高性能、太牛逼啦!

点击阅读原文,前往学习SpringCloud实战项目

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/46241
推荐阅读
相关标签
  

闽ICP备14008679号