2021 最新版 Spring Boot 速記教程
本文來(lái)源:http://r6d.cn/X6FP
結(jié)束了前面的《Spring 源碼深度學(xué)習(xí)》,八月給自己放松了一下,看了幾本小說(shuō)和電視劇,還有寫(xiě)一個(gè)工作中用到的小工具,周報(bào)數(shù)據(jù)渲染的前端界面(前端是真的難)。
當(dāng)然技術(shù)上的學(xué)習(xí)也要注意,所以看了松哥寫(xiě)的《Spring Boot + Vue 全棧開(kāi)發(fā)》,來(lái)系統(tǒng)學(xué)習(xí) SpringBoot,下面是簡(jiǎn)單的速記,根據(jù)使用場(chǎng)景可以快速定位到知識(shí)點(diǎn):
Demo 腳手架項(xiàng)目地址:
https://github.com/Vip-Augus/springboot-note
Table of Contents generated with DocToc
SpringBoot 速記 一、引入依賴(lài) 二、配置 Swagger 參數(shù) 一、引入依賴(lài) 二、配置郵箱的參數(shù) 三、寫(xiě)模板和發(fā)送內(nèi)容 一、引用 Redis 依賴(lài) 二、參數(shù)配置 三、代碼使用 一、添加 mybatis 和 druid 依賴(lài) 二、配置數(shù)據(jù)庫(kù)和連接池參數(shù) 三、其他 mybatis 配置 @ExceptionHandler 錯(cuò)誤處理 @ModelAttribute 視圖屬性 常規(guī)配置 HTTPS 配置 構(gòu)建項(xiàng)目 SpringBoot 基礎(chǔ)配置 Spring Boot Starters @SpringBootApplication Web 容器配置 @ConfigurationProperties Profile @ControllerAdvice 用來(lái)處理全局?jǐn)?shù)據(jù) CORS 支持,跨域資源共享 注冊(cè) MVC 攔截器 開(kāi)啟 AOP 切面控制 整合 Mybatis 和 Druid 整合 Redis 發(fā)送 HTML 樣式的郵件 整合 Swagger (API 文檔) 總結(jié) 參考資料
構(gòu)建項(xiàng)目
相比于使用 IDEA 的模板創(chuàng)建項(xiàng)目,我更推薦的是在 Spring 官網(wǎng)上選擇參數(shù)一步生成項(xiàng)目。
https://start.spring.io/
關(guān)于 IDEA 發(fā)布過(guò)很多文字,可以關(guān)注微信公眾號(hào) Java后端,關(guān)注后輸入 666 命令下載 Spring Boot 和 IDEA 相關(guān)文字的 PDF。
我們只需要做的事情,就是修改組織名和項(xiàng)目名,點(diǎn)擊 Generate the project,下載到本地,然后使用 IDEA 打開(kāi)
這個(gè)時(shí)候,不需要任何配置,點(diǎn)擊 Application 類(lèi)的 run 方法就能直接啟動(dòng)項(xiàng)目。
SpringBoot 基礎(chǔ)配置
Spring Boot Starters
引用自參考資料 1 描述:
“starter的理念:starter 會(huì)把所有用到的依賴(lài)都給包含進(jìn)來(lái),避免了開(kāi)發(fā)者自己去引入依賴(lài)所帶來(lái)的麻煩。需要注意的是不同的 starter 是為了解決不同的依賴(lài),所以它們內(nèi)部的實(shí)現(xiàn)可能會(huì)有很大的差異,例如 jpa 的 starter 和 Redis 的 starter 可能實(shí)現(xiàn)就不一樣,這是因?yàn)?starter 的本質(zhì)在于 synthesize,這是一層在邏輯層面的抽象,也許這種理念有點(diǎn)類(lèi)似于 Docker,因?yàn)樗鼈兌际窃谧鲆粋€(gè)“包裝”的操作,如果你知道 Docker 是為了解決什么問(wèn)題的,也許你可以用 Docker 和 starter 做一個(gè)類(lèi)比。
”
我們知道在 SpringBoot 中很重要的一個(gè)概念就是,「約定優(yōu)于配置」,通過(guò)特定方式的配置,可以減少很多步驟來(lái)實(shí)現(xiàn)想要的功能。
例如如果我們想要使用緩存 Redis
在之前的可能需要通過(guò)以下幾個(gè)步驟:
在 pom文件引入特定版本的redis在 .properties文件中配置參數(shù)根據(jù)參數(shù),新建一個(gè)又一個(gè) jedis連接定義一個(gè)工具類(lèi),手動(dòng)創(chuàng)建連接池來(lái)管理
經(jīng)歷了上面的步驟,我們才能正式使用 Redis
但在 Spring Boot 中,一切因?yàn)?Starter 變得簡(jiǎn)單
在 pom文件中引入spring-boot-starter-data-redis在 .properties文件中配置參數(shù)
通過(guò)上面兩個(gè)步驟,配置自動(dòng)生效,具體生效的 bean 是 RedisAutoConfiguration,自動(dòng)配置類(lèi)的名字都有一個(gè)特點(diǎn),叫做 xxxAutoConfiguration。
可以來(lái)簡(jiǎn)單看下這個(gè)類(lèi):
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({?LettuceConnectionConfiguration.class,?JedisConnectionConfiguration.class?})
public?class?RedisAutoConfiguration?{
?@Bean
?@ConditionalOnMissingBean(name?=?"redisTemplate")
?public?RedisTemplate可以看到,Redis 自動(dòng)配置類(lèi),讀取了以 spring.redis 為前綴的配置,然后加載 redisTemplate 到容器中,然后我們?cè)趹?yīng)用中就能使用 RedisTemplate 來(lái)對(duì)緩存進(jìn)行操作~(還有很多細(xì)節(jié)沒(méi)有細(xì)說(shuō),例如 @ConditionalOnMissingBean 先留個(gè)坑(●′?`●)?)
@Autowired
private?RedisTemplate?redisTemplate;
ValueOperations?ops2?=?redisTemplate.opsForValue();
Book?book?=?(Book)?ops2.get("b1");
@SpringBootApplication
該注解是加載項(xiàng)目的啟動(dòng)類(lèi)上的,而且它是一個(gè)組合注解:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters?=?{?@Filter(type?=?FilterType.CUSTOM,?classes?=?TypeExcludeFilter.class),
??@Filter(type?=?FilterType.CUSTOM,?classes?=?AutoConfigurationExcludeFilter.class)?})
public?@interface?SpringBootApplication?{...}
下面是這三個(gè)核心注解的解釋?zhuān)?/p>注解名 解釋 @SpringBootConfiguration 表明這是一個(gè)配置類(lèi),開(kāi)發(fā)者可以在這個(gè)類(lèi)中配置 Bean @EnableAutoConfiguration 表示開(kāi)啟自動(dòng)化配置 @ComponentScan 完成包掃描,默認(rèn)掃描的類(lèi)位于當(dāng)前類(lèi)所在包的下面
通過(guò)該注解,我們執(zhí)行 mian 方法:
SpringApplication.run(SpringBootLearnApplication.class,?args);
就可以啟動(dòng)一個(gè) SpringApplicaiton 應(yīng)用了。
Web 容器配置
常規(guī)配置
| 配置名 | 解釋 |
|---|---|
| server.port=8081 | 配置了容器的端口號(hào),默認(rèn)是 8080 |
| server.error.path=/error | 配置了項(xiàng)目出錯(cuò)時(shí)跳轉(zhuǎn)的頁(yè)面 |
| server.servlet.session.timeout=30m | session 失效時(shí)間,m 表示分鐘,如果不寫(xiě)單位,默認(rèn)是秒 s |
| server.servlet.context-path=/ | 項(xiàng)目名稱(chēng),不配置時(shí)默認(rèn)為/。配置后,訪問(wèn)時(shí)需加上前綴 |
| server.tomcat.uri-encoding=utf-8 | Tomcat 請(qǐng)求編碼格式 |
| server.tomcat.max-threads=500 | Tomcat 最大線程數(shù) |
| server.tomcat.basedir=/home/tmp | Tomcat 運(yùn)行日志和臨時(shí)文件的目錄,如不配置,默認(rèn)使用系統(tǒng)的臨時(shí)目錄 |
HTTPS 配置
| 配置名 | 解釋 |
|---|---|
| server.ssl.key-store=xxx | 秘鑰文件名 |
| server.ssl.key-alias=xxx | 秘鑰別名 |
| server.ssl.key-store-password=123456 | 秘鑰密碼 |
想要詳細(xì)了解如何配置 HTTPS,可以參考這篇文章 Spring Boot 使用SSL-HTTPS
@ConfigurationProperties
這個(gè)注解可以放在類(lèi)上或者 @Bean 注解所在方法上,這樣 SpringBoot 就能夠從配置文件中,讀取特定前綴的配置,將屬性值注入到對(duì)應(yīng)的屬性。
使用例子:
@Configuration
@ConfigurationProperties(prefix?=?"spring.datasource")
public?class?DruidConfigBean?{
????private?Integer?initialSize;
????private?Integer?minIdle;
????private?Integer?maxActive;
????
????private?List?customs;
????
????...
}
application.properties
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.customs=test1,test2,test3
其中,如果對(duì)象是列表結(jié)構(gòu),可以在配置文件中使用 , 逗號(hào)進(jìn)行分割,然后注入到相應(yīng)的屬性中。
Profile
使用該屬性,可以快速切換配置文件,在 SpringBoot 默認(rèn)約定中,不同環(huán)境下配置文件名稱(chēng)規(guī)則為 application-{profile}.propertie,profile 占位符表示當(dāng)前環(huán)境的名稱(chēng)。
1、配置 application.properties
spring.profiles.active=dev
2、在代碼中配置
在啟動(dòng)類(lèi)的 main 方法上添加 setAdditionalProfiles("{profile}");
SpringApplicationBuilder?builder?=?new?SpringApplicationBuilder(SpringBootLearnApplication.class);
builder.application().setAdditionalProfiles("prod");
builder.run(args);
3、啟動(dòng)參數(shù)配置
java?-jar?demo.jar?--spring.active.profile=dev
@ControllerAdvice 用來(lái)處理全局?jǐn)?shù)據(jù)
@ControllerAdvice 是 @Controller 的增強(qiáng)版。主要用來(lái)處理全局?jǐn)?shù)據(jù),一般搭配 @ExceptionHandler 、@ModelAttribute 以及 @InitBinder 使用。
@ExceptionHandler 錯(cuò)誤處理
/**
?*?加強(qiáng)版控制器,攔截自定義的異常處理
?*
?*/
@ControllerAdvice
public?class?CustomExceptionHandler?{
????
????//?指定全局?jǐn)r截的異常類(lèi)型,統(tǒng)一處理
????@ExceptionHandler(MaxUploadSizeExceededException.class)
????public?void?uploadException(MaxUploadSizeExceededException?e,?HttpServletResponse?response)?throws?IOException?{
????????response.setContentType("text/html;charset=utf-8");
????????PrintWriter?out?=?response.getWriter();
????????out.write("上傳文件大小超出限制");
????????out.flush();
????????out.close();
????}
}
@ModelAttribute 視圖屬性
@ControllerAdvice
public?class?CustomModelAttribute?{
????
????//?
????@ModelAttribute(value?=?"info")
????public?Map?userInfo()?throws?IOException?{
????????Map?map?=?new?HashMap<>();
????????map.put("test",?"testInfo");
????????return?map;
????}
}
@GetMapping("/hello")
public?String?hello(Model?model)?{
????Map?map?=?model.asMap();
????Map?infoMap?=?(Map)?map.get("info");
????return?infoMap.get("test");
}
key : @ModelAttribute注解中的value屬性使用場(chǎng)景:任何請(qǐng)求 controller類(lèi),通過(guò)方法參數(shù)中的Model都可以獲取value對(duì)應(yīng)的屬性關(guān)注公眾號(hào)Java后端編程,回復(fù) Java 獲取最新學(xué)習(xí)資料 。
CORS 支持,跨域資源共享
CORS(Cross-Origin Resource Sharing),跨域資源共享技術(shù),目的是為了解決前端的跨域請(qǐng)求。
“引用:當(dāng)一個(gè)資源從與該資源本身所在服務(wù)器不同的域或端口請(qǐng)求一個(gè)資源時(shí),資源會(huì)發(fā)起一個(gè)跨域HTTP請(qǐng)求
”
詳細(xì)可以參考這篇文章-springboot系列文章之實(shí)現(xiàn)跨域請(qǐng)求(CORS),這里只是記錄一下如何使用:
例如在我的前后端分離 demo 中,如果沒(méi)有通過(guò) Nginx 轉(zhuǎn)發(fā),那么將會(huì)提示如下信息:
“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’
”
為了解決這個(gè)問(wèn)題,在前端不修改的情況下,需要后端加上如下兩行代碼:
//?第一行,支持的域
@CrossOrigin(origins?=?"http://localhost:3000")
@RequestMapping(value?=?"/login",?method?=?RequestMethod.GET)
@ResponseBody
public?String?login(HttpServletResponse?response)?{
????//?第二行,響應(yīng)體添加頭信息(這一行是解決上面的提示)
????response.setHeader("Access-Control-Allow-Credentials",?"true");
????return?HttpRequestUtils.login();
}
注冊(cè) MVC 攔截器
在 MVC 模塊中,也提供了類(lèi)似 AOP 切面管理的擴(kuò)展,能夠擁有更加精細(xì)的攔截處理能力。
核心在于該接口:HandlerInterceptor,使用方式如下:
/**
?*?自定義?MVC?攔截器
?*/
public?class?MyInterceptor?implements?HandlerInterceptor?{
????@Override
????public?boolean?preHandle(HttpServletRequest?request,?HttpServletResponse?response,?Object?handler)?throws?Exception?{
????????//?在?controller?方法之前調(diào)用
????????return?true;
????}
????@Override
????public?void?postHandle(HttpServletRequest?request,?HttpServletResponse?response,?Object?handler,?ModelAndView?modelAndView)?throws?Exception?{
????????//?在?controller?方法之后調(diào)用
????}
????@Override
????public?void?afterCompletion(HttpServletRequest?request,?HttpServletResponse?response,?Object?handler,?Exception?ex)?throws?Exception?{
????????//?在?postHandle?方法之后調(diào)用
????}
}
注冊(cè)代碼:
/**
?*?全局控制的?mvc?配置
?*/
@Configuration
public?class?MyWebMvcConfig?implements?WebMvcConfigurer?{
????@Override
????public?void?addInterceptors(InterceptorRegistry?registry)?{
????????registry.addInterceptor(new?MyInterceptor())
????????????????//?表示攔截的?URL
????????????????.addPathPatterns("/**")
????????????????//?表示需要排除的路徑
????????????????.excludePathPatterns("/hello");
????}
}
攔截器執(zhí)行順序:preHandle -> controller -> postHandle -> afterCompletion,同時(shí)需要注意的是,只有 preHandle 方法返回 true,后面的方法才會(huì)繼續(xù)執(zhí)行。
開(kāi)啟 AOP 切面控制
切面注入是老生常談的技術(shù),之前學(xué)習(xí) Spring 時(shí)也有了解,可以參考我之前寫(xiě)過(guò)的文章參考一下:
Spring自定義注解實(shí)現(xiàn)AOP
Spring 源碼學(xué)習(xí)(八) AOP 使用和實(shí)現(xiàn)原理
在 SpringBoot 中,使用起來(lái)更加簡(jiǎn)便,只需要加入該依賴(lài),使用方法與上面一樣。
????org.springframework.boot
????spring-boot-starter-aop
整合 Mybatis 和 Druid
SpringBoot 整合數(shù)據(jù)庫(kù)操作,目前主流使用的是 Druid 連接池和 Mybatis 持久層,同樣的,starter 提供了簡(jiǎn)潔的整合方案
項(xiàng)目結(jié)構(gòu)如下:
一、添加 mybatis 和 druid 依賴(lài)
?
????org.mybatis.spring.boot
????mybatis-spring-boot-starter
????1.3.2
????com.alibaba
????druid-spring-boot-starter
????1.1.18
二、配置數(shù)據(jù)庫(kù)和連接池參數(shù)
#?數(shù)據(jù)庫(kù)配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=12345678
#?druid?配置
spring.datasource.druid.initial-size=5
spring.datasource.druid.max-active=20
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-wait=60000
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
spring.datasource.druid.max-open-prepared-statements=20
spring.datasource.druid.validation-query=SELECT?1
spring.datasource.druid.validation-query-timeout=30000
spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.test-on-return=false
spring.datasource.druid.test-while-idle=false
#spring.datasource.druid.time-between-eviction-runs-millis=
#spring.datasource.druid.min-evictable-idle-time-millis=
#spring.datasource.druid.max-evictable-idle-time-millis=10000
#?Druid?stat?filter?config
spring.datasource.druid.filters=stat,wall
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
#?session?監(jiān)控
spring.datasource.druid.web-stat-filter.session-stat-enable=true
spring.datasource.druid.web-stat-filter.session-stat-max-count=10
spring.datasource.druid.web-stat-filter.principal-session-name=admin
spring.datasource.druid.web-stat-filter.principal-cookie-name=admin
spring.datasource.druid.web-stat-filter.profile-enable=true
#?stat?監(jiān)控
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*
spring.datasource.druid.filter.stat.db-type=mysql
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=1000
spring.datasource.druid.filter.stat.merge-sql=true
spring.datasource.druid.filter.wall.enabled=true
spring.datasource.druid.filter.wall.db-type=mysql
spring.datasource.druid.filter.wall.config.delete-allow=true
spring.datasource.druid.filter.wall.config.drop-table-allow=false
#?Druid?manage?page?config
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
spring.datasource.druid.stat-view-servlet.reset-enable=true
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
#spring.datasource.druid.stat-view-servlet.allow=
#spring.datasource.druid.stat-view-servlet.deny=
spring.datasource.druid.aop-patterns=cn.sevenyuan.demo.*
三、其他 mybatis 配置
本地工程,將 xml 文件放入 resources 資源文件夾下,所以需要加入以下配置,讓?xiě)?yīng)用進(jìn)行識(shí)別:
?
????
????????
????????????src/main/resources
????????????
????????????????**/*
????????????
????????
????
????...
通過(guò)上面的配置,我本地開(kāi)啟了三個(gè)頁(yè)面的監(jiān)控:SQL 、 URL 和 Sprint 監(jiān)控,如下圖:
通過(guò)上面的配置,SpringBoot 很方便的就整合了 Druid 和 mybatis,同時(shí)根據(jù)在 properties 文件中配置的參數(shù),開(kāi)啟了 Druid 的監(jiān)控。
但我根據(jù)上面的配置,始終開(kāi)啟不了 session 監(jiān)控,所以如果需要配置 session 監(jiān)控或者調(diào)整參數(shù)具體配置,可以查看官方網(wǎng)站
整合 Redis
我用過(guò) Redis 和 NoSQL,但最熟悉和常用的,還是 Redis ,所以這里記錄一下如何整合
一、引用 Redis 依賴(lài)
????org.springframework.boot
????spring-boot-starter-data-redis
????
????????
????????????lettuce-core
????????????io.lettuce
????????
????
????redis.clients
????jedis
二、參數(shù)配置
#?redis?配置
spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=-1ms
spring.redis.jedis.pool.min-idle=0
三、代碼使用
@Autowired
private?RedisTemplate?redisTemplate;
@Autowired
private?StringRedisTemplate?stringRedisTemplate;
@GetMapping("/testRedis")
public?Book?getForRedis()?{
????ValueOperations?ops1?=?stringRedisTemplate.opsForValue();
????ops1.set("name",?"Go?語(yǔ)言實(shí)戰(zhàn)");
????String?name?=?ops1.get("name");
????System.out.println(name);
????ValueOperations?ops2?=?redisTemplate.opsForValue();
????Book?book?=?(Book)?ops2.get("b1");
????if?(book?==?null)?{
????????book?=?new?Book("Go?語(yǔ)言實(shí)戰(zhàn)",?2,?"none?name",?BigDecimal.ONE);
????????ops2.set("b1",?book);
????}
????return?book;
}
這里只是簡(jiǎn)單記錄引用和使用方式,更多功能可以看這里:
發(fā)送 HTML 樣式的郵件
之前也使用過(guò),所以可以參考這篇文章:
一、引入依賴(lài)
?
????org.springframework.boot
????spring-boot-starter-mail
????org.springframework.boot
????spring-boot-starter-thymeleaf
二、配置郵箱的參數(shù)
#?mail
spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=xxxxxxxx
spring.mail.password=xxxxxxxx
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true
如果使用的是 QQ 郵箱,需要在郵箱的設(shè)置中獲取授權(quán)碼,填入上面的 password 中
三、寫(xiě)模板和發(fā)送內(nèi)容
MailServiceImpl.java
@Autowired
private?JavaMailSender?javaMailSender;
@Override
public?void?sendHtmlMail(String?from,?String?to,?String?subject,?String?content)?{
????try?{
????????MimeMessage?message?=?javaMailSender.createMimeMessage();
????????MimeMessageHelper?helper?=?new?MimeMessageHelper(message,?true);
????????helper.setFrom(from);
????????helper.setTo(to);
????????helper.setSubject(subject);
????????helper.setText(content,?true);
????????javaMailSender.send(message);
????}?catch?(MessagingException?e)?{
????????System.out.println("發(fā)送郵件失敗");
????????log.error("發(fā)送郵件失敗",?e);
????}
}
mailtemplate.html
"en"?xmlns:th="http://www.thymeleaf.org">
????"UTF-8">
????郵件
"${subject}">
書(shū)籍清單
????"1">
????????
????????????圖書(shū)編號(hào)
????????????圖書(shū)名稱(chēng)
????????????圖書(shū)作者
????????
????????"book:${books}">
????????????"${book.id}">
????????????"${book.name}">
????????????"${book.author}">
????????
????
test.java
@Autowired
private?MailService?mailService;
@Autowired
private?TemplateEngine?templateEngine;
????
@Test
public?void?sendThymeleafMail()?{
????Context?context?=?new?Context();
????context.setVariable("subject",?"圖書(shū)清冊(cè)");
????List?books?=?Lists.newArrayList();
????books.add(new?Book("Go?語(yǔ)言基礎(chǔ)",?1,?"nonename",?BigDecimal.TEN));
????books.add(new?Book("Go?語(yǔ)言實(shí)戰(zhàn)",?2,?"nonename",?BigDecimal.TEN));
????books.add(new?Book("Go?語(yǔ)言進(jìn)階",?3,?"nonename",?BigDecimal.TEN));
????context.setVariable("books",?books);
????String?mail?=?templateEngine.process("mailtemplate.html",?context);
????mailService.sendHtmlMail("[email protected]",?"[email protected]",?"圖書(shū)清冊(cè)",?mail);
}
通過(guò)上面簡(jiǎn)單步驟,就能夠在代碼中發(fā)送郵件,例如我們每周要寫(xiě)周報(bào),統(tǒng)計(jì)系統(tǒng)運(yùn)行狀態(tài),可以設(shè)定定時(shí)任務(wù),統(tǒng)計(jì)數(shù)據(jù),然后自動(dòng)化發(fā)送郵件。
整合 Swagger (API 文檔)
一、引入依賴(lài)
????io.springfox
????springfox-swagger2
????2.9.2
????io.springfox
????springfox-swagger-ui
????2.9.2
二、配置 Swagger 參數(shù)
SwaggerConfig.java
@Configuration
@EnableSwagger2
@EnableWebMvc
public?class?SwaggerConfig?{
????@Bean
????Docket?docket()?{
????????return?new?Docket(DocumentationType.SWAGGER_2)
????????????????.select()
????????????????.apis(RequestHandlerSelectors.basePackage("cn.sevenyuan.demo.controller"))
????????????????.paths(PathSelectors.any())
????????????????.build().apiInfo(
????????????????????????new?ApiInfoBuilder()
????????????????????????????????.description("Spring?Boot?learn?project")
????????????????????????????????.contact(new?Contact("JingQ",?"https://github.com/vip-augus",?"[email protected]"))
????????????????????????????????.version("v1.0")
????????????????????????????????.title("API?測(cè)試文檔")
????????????????????????????????.license("Apache2.0")
????????????????????????????????.licenseUrl("http://www.apache.org/licenese/LICENSE-2.0")
????????????????????????????????.build());
????}
}
設(shè)置頁(yè)面 UI
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds?=?60)
public?class?MyWebMvcConfig?implements?WebMvcConfigurer?{
????@Override
????public?void?addResourceHandlers(ResourceHandlerRegistry?registry)?{
????????registry.addResourceHandler("swagger-ui.html")
????????????????.addResourceLocations("classpath:/META-INF/resources/");
????????registry.addResourceHandler("/webjars/**")
????????????????.addResourceLocations("classpath:/META-INF/resources/webjars/");
????}
}
通過(guò)這樣就能夠識(shí)別 @ApiOperation 等接口標(biāo)志,在網(wǎng)頁(yè)查看 API 文檔,參考文檔:Spring Boot實(shí)戰(zhàn):集成Swagger2
總結(jié)
這邊總結(jié)的整合經(jīng)驗(yàn),只是很基礎(chǔ)的配置,在學(xué)習(xí)的初期,秉著先跑起來(lái),然后不斷完善和精進(jìn)學(xué)習(xí)。
而且單一整合很容易,但多個(gè)依賴(lài)會(huì)出現(xiàn)想不到的錯(cuò)誤,所以在解決環(huán)境問(wèn)題時(shí)遇到很多坑,想要使用基礎(chǔ)的腳手架,可以嘗試跑我上傳的項(xiàng)目。
數(shù)據(jù)庫(kù)腳本在 resources 目錄的 test.sql 文件中
參考資料
1、Spring Boot Starters
2、Spring Boot 使用SSL-HTTPS
3、Spring Boot(07)——ConfigurationProperties介紹
4、springboot系列文章之實(shí)現(xiàn)跨域請(qǐng)求(CORS)
5、Spring Data Redis(一)–解析RedisTemplate
6、Spring Boot實(shí)戰(zhàn):集成Swagger2
PS:歡迎在留言區(qū)留下你的觀點(diǎn),一起討論提高。如果今天的文章讓你有新的啟發(fā),歡迎轉(zhuǎn)發(fā)分享給更多人。
-?END -
最近熱門(mén)閱讀
同事寫(xiě)了一個(gè)update,誤用一個(gè)雙引號(hào),生產(chǎn)數(shù)據(jù)全變0了!
「開(kāi)源」目前見(jiàn)過(guò)的最好的開(kāi)源OA產(chǎn)品
點(diǎn)贊是最大的支持?




