01.21 SpringBoot 速記

Demo 腳手架項目地址:

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

Table of Contents generated with DocToc

  • SpringBoot 速記構建項目SpringBoot 基礎配置Spring Boot Starters@SpringBootApplicationWeb 容器配置常規配置HTTPS 配置@ConfigurationPropertiesProfile@ControllerAdvice 用來處理全局數據@ExceptionHandler 錯誤處理@ModelAttribute 視圖屬性CORS 支持,跨域資源共享註冊 MVC 攔截器開啟 AOP 切面控制整合 Mybatis 和 Druid一、添加 mybatis 和 druid 依賴二、配置數據庫和連接池參數三、其他 mybatis 配置整合 Redis一、引用 Redis 依賴二、參數配置三、代碼使用發送 HTML 樣式的郵件一、引入依賴二、配置郵箱的參數三、寫模板和發送內容整合 Swagger (API 文檔)一、引入依賴二、配置 Swagger 參數總結參考資料

構建項目

相比於使用 IDEA 的模板創建項目,我更推薦的是在 Spring 官網上選擇參數一步生成項目

https://start.spring.io/


SpringBoot 速記


我們只需要做的事情,就是修改組織名和項目名,點擊 Generate the project,下載到本地,然後使用 IDEA 打開

這個時候,不需要任何配置,點擊 Application 類的 run 方法就能直接啟動項目。


SpringBoot 基礎配置

Spring Boot Starters

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。

可以來簡單看下這個類:

<code>@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {

\t@Bean
\t@ConditionalOnMissingBean(name = "redisTemplate")
\tpublic RedisTemplate<object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
\t\t\tthrows UnknownHostException {
\t\tRedisTemplate<object> template = new RedisTemplate<>();
\t\ttemplate.setConnectionFactory(redisConnectionFactory);
\t\treturn template;
\t}

\t@Bean
\t@ConditionalOnMissingBean
\tpublic StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)
\t\t\tthrows UnknownHostException {
\t\tStringRedisTemplate template = new StringRedisTemplate();
\t\ttemplate.setConnectionFactory(redisConnectionFactory);
\t\treturn template;
\t}

}

@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {...}
/<object>/<object>/<code>

可以看到,Redis 自動配置類,讀取了以 spring.redis 為前綴的配置,然後加載 redisTemplate 到容器中,然後我們在應用中就能使用 RedisTemplate 來對緩存進行操作~(還有很多細節沒有細說,例如 @ConditionalOnMissingBean 先留個坑(●´∀`●)ノ)

<code>@Autowired
private RedisTemplate redisTemplate;

ValueOperations ops2 = redisTemplate.opsForValue();
Book book = (Book) ops2.get("b1");
/<code>

@SpringBootApplication

該註解是加載項目的啟動類上的,而且它是一個組合註解:

<code>@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
\t\t@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {...}
/<code>

下面是這三個核心註解的解釋:

註解名解釋@SpringBootConfiguration表明這是一個配置類,開發者可以在這個類中配置 Bean@EnableAutoConfiguration表示開啟自動化配置@ComponentScan完成包掃描,默認掃描的類位於當前類所在包的下面

通過該註解,我們執行 mian 方法:

<code>SpringApplication.run(SpringBootLearnApplication.class, args);
/<code>

就可以啟動一個 SpringApplicaiton 應用了。


Web 容器配置

常規配置

配置名解釋server.port=8081配置了容器的端口號,默認是 8080server.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 就能夠從配置文件中,讀取特定前綴的配置,將屬性值注入到對應的屬性。

使用例子:

<code>@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidConfigBean {

private Integer initialSize;


private Integer minIdle;

private Integer maxActive;

private List<string> customs;

...
}
/<string>/<code>

application.properties

<code>spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.customs=test1,test2,test3
/<code>

其中,如果對象是列表結構,可以在配置文件中使用 , 逗號進行分割,然後注入到相應的屬性中。


Profile

使用該屬性,可以快速切換配置文件,在 SpringBoot 默認約定中,不同環境下配置文件名稱規則為 application-{profile}.propertie,profile 佔位符表示當前環境的名稱。

1、配置 application.properties

<code>spring.profiles.active=dev
/<code>

2、在代碼中配置 在啟動類的 main 方法上添加 setAdditionalProfiles("{profile}");

<code>SpringApplicationBuilder builder = new SpringApplicationBuilder(SpringBootLearnApplication.class);
builder.application().setAdditionalProfiles("prod");
builder.run(args);
/<code>

3、啟動參數配置

<code>java -jar demo.jar --spring.active.profile=dev
/<code>

@ControllerAdvice 用來處理全局數據

@ControllerAdvice 是 @Controller 的增強版。主要用來處理全局數據,一般搭配 @ExceptionHandler 、@ModelAttribute 以及 @InitBinder 使用。

@ExceptionHandler 錯誤處理

<code>/**
* 加強版控制器,攔截自定義的異常處理
*
*/
@ControllerAdvice
public class CustomExceptionHandler {

// 指定全局攔截的異常類型,統一處理
@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();
}
}
/<code>

@ModelAttribute 視圖屬性

<code>@ControllerAdvice
public class CustomModelAttribute {

//
@ModelAttribute(value = "info")
public Map<string> userInfo() throws IOException {
Map<string> map = new HashMap<>();
map.put("test", "testInfo");
return map;
}

}


@GetMapping("/hello")
public String hello(Model model) {
Map<string> map = model.asMap();
Map<string> infoMap = (Map<string>) map.get("info");
return infoMap.get("test");
}
/<string>/<string>/<string>/<string>/<string>/<code>
  • 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’

為了解決這個問題,在前端不修改的情況下,需要後端加上如下兩行代碼:

<code>// 第一行,支持的域
@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping(value = "/login", method = RequestMethod.GET)
@ResponseBody
public String login(HttpServletResponse response) {
// 第二行,響應體添加頭信息(這一行是解決上面的提示)
response.setHeader("Access-Control-Allow-Credentials", "true");
return HttpRequestUtils.login();
}
/<code>

註冊 MVC 攔截器

在 MVC 模塊中,也提供了類似 AOP 切面管理的擴展,能夠擁有更加精細的攔截處理能力。

核心在於該接口:HandlerInterceptor,使用方式如下:

<code>/**
* 自定義 MVC 攔截器
*/
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 在 controller 方法之前調用
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 在 controller 方法之後調用
}

@Override

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 在 postHandle 方法之後調用
}
}
/<code>

註冊代碼:

<code>/**
* 全局控制的 mvc 配置
*/
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor())
// 表示攔截的 URL
.addPathPatterns("/**")
// 表示需要排除的路徑
.excludePathPatterns("/hello");
}
}
/<code>

攔截器執行順序: preHandle -> controller -> postHandle -> afterCompletion,同時需要注意的是,只有 preHandle 方法返回 true,後面的方法才會繼續執行。


開啟 AOP 切面控制

切面注入是老生常談的技術,之前學習 Spring 時也有了解,可以參考我之前寫過的文章參考一下:

Spring自定義註解實現AOP

Spring 源碼學習(八) AOP 使用和實現原理

在 SpringBoot 中,使用起來更加簡便,只需要加入該依賴,使用方法與上面一樣。

<code><dependency>
<groupid>org.springframework.boot/<groupid>
<artifactid>spring-boot-starter-aop/<artifactid>
/<dependency>
/<code>

整合 Mybatis 和 Druid

SpringBoot 整合數據庫操作,目前主流使用的是 Druid 連接池和 Mybatis 持久層,同樣的,starter 提供了簡潔的整合方案

項目結構如下:


SpringBoot 速記


一、添加 mybatis 和 druid 依賴

<code> <dependency>
<groupid>org.mybatis.spring.boot/<groupid>
<artifactid>mybatis-spring-boot-starter/<artifactid>
<version>1.3.2/<version>
/<dependency>

<dependency>
<groupid>com.alibaba/<groupid>
<artifactid>druid-spring-boot-starter/<artifactid>
<version>1.1.18/<version>
/<dependency>
/<code>

二、配置數據庫和連接池參數

<code># 數據庫配置
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 監控
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 監控
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.*
/<code>

三、其他 mybatis 配置

本地工程,將 xml 文件放入 resources 資源文件夾下,所以需要加入以下配置,讓應用進行識別:

<code> <build>
<resources>
<resource>
<directory>src/main/resources/<directory>
<includes>
<include>**/*/<include>
/<includes>
/<resource>
/<resources>
...
/<build>
/<code>

通過上面的配置,我本地開啟了三個頁面的監控:SQL 、 URL 和 Sprint 監控,如下圖:

SpringBoot 速記

通過上面的配置,SpringBoot 很方便的就整合了 Druid 和 mybatis,同時根據在 properties 文件中配置的參數,開啟了 Druid 的監控。

但我根據上面的配置,始終開啟不了 session 監控,所以如果需要配置 session 監控或者調整參數具體配置,可以查看官方網站

alibaba/druid


整合 Redis

我用過 Redis 和 NoSQL,但最熟悉和常用的,還是 Redis ,所以這裡記錄一下如何整合

一、引用 Redis 依賴

<code><dependency>
<groupid>org.springframework.boot/<groupid>
<artifactid>spring-boot-starter-data-redis/<artifactid>
<exclusions>
<exclusion>
<artifactid>lettuce-core/<artifactid>
<groupid>io.lettuce/<groupid>
/<exclusion>
/<exclusions>
/<dependency>

<dependency>
<groupid>redis.clients/<groupid>
<artifactid>jedis/<artifactid>
/<dependency>
/<code>

二、參數配置

<code># 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
/<code>

三、代碼使用

<code>@Autowired
private RedisTemplate redisTemplate;

@Autowired

private StringRedisTemplate stringRedisTemplate;

@GetMapping("/testRedis")
public Book getForRedis() {
ValueOperations<string> ops1 = stringRedisTemplate.opsForValue();
ops1.set("name", "Go 語言實戰");
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 語言實戰", 2, "none name", BigDecimal.ONE);
ops2.set("b1", book);
}
return book;
}
/<string>/<code>

這裡只是簡單記錄引用和使用方式,更多功能可以看這裡:Spring Data Redis(一)–解析RedisTemplate


發送 HTML 樣式的郵件

之前也使用過,所以可以參考這篇文章:Java整合Spring發送郵件

一、引入依賴

<code> 
<dependency>
<groupid>org.springframework.boot/<groupid>
<artifactid>spring-boot-starter-mail/<artifactid>
/<dependency>

<dependency>
<groupid>org.springframework.boot/<groupid>
<artifactid>spring-boot-starter-thymeleaf/<artifactid>
/<dependency>
/<code>

二、配置郵箱的參數

<code># 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
/<code>

如果使用的是 QQ 郵箱,需要在郵箱的設置中獲取授權碼,填入上面的 password 中

三、寫模板和發送內容

MailServiceImpl.java

<code>@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("發送郵件失敗");
log.error("發送郵件失敗", e);
}
}
/<code>

mailtemplate.html

<code>



<title>郵件/<title>



書籍清單
<table>

圖書編號
圖書名稱
圖書作者






/<table>



/<code>

test.java

<code>
@Autowired
private MailService mailService;

@Autowired
private TemplateEngine templateEngine;

@Test
public void sendThymeleafMail() {
Context context = new Context();
context.setVariable("subject", "圖書清冊");

List<book> books = Lists.newArrayList();
books.add(new Book("Go 語言基礎", 1, "nonename", BigDecimal.TEN));
books.add(new Book("Go 語言實戰", 2, "nonename", BigDecimal.TEN));
books.add(new Book("Go 語言進階", 3, "nonename", BigDecimal.TEN));
context.setVariable("books", books);
String mail = templateEngine.process("mailtemplate.html", context);
mailService.sendHtmlMail("[email protected]", "[email protected]", "圖書清冊", mail);
}
/<book>/<code>

通過上面簡單步驟,就能夠在代碼中發送郵件,例如我們每週要寫週報,統計系統運行狀態,可以設定定時任務,統計數據,然後自動化發送郵件。


整合 Swagger (API 文檔)

一、引入依賴

<code>
<dependency>
<groupid>io.springfox/<groupid>
<artifactid>springfox-swagger2/<artifactid>
<version>2.9.2/<version>
/<dependency>

<dependency>
<groupid>io.springfox/<groupid>
<artifactid>springfox-swagger-ui/<artifactid>
<version>2.9.2/<version>
/<dependency>
/<code>

二、配置 Swagger 參數

SwaggerConfig.java

<code>@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 測試文檔")
.license("Apache2.0")
.licenseUrl("http://www.apache.org/licenese/LICENSE-2.0")
.build());

}
}
/<code>

設置頁面 UI

<code>@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/");
}
}
/<code>

通過這樣就能夠識別 @ApiOperation 等接口標誌,在網頁查看 API 文檔,參考文檔:Spring Boot實戰:集成Swagger2


總結

這邊總結的整合經驗,只是很基礎的配置,在學習的初期,秉著先跑起來,然後不斷完善和精進學習。

而且單一整合很容易,但多個依賴會出現想不到的錯誤,所以在解決環境問題時遇到很多坑,想要使用基礎的腳手架,可以嘗試跑我上傳的項目。

數據庫腳本在 resources 目錄的 test.sql 文件中


分享到:


相關文章: