1. 什么是SpringBoot
Spring Boot 是 Spring 社區(qū)較新的一個項目系枪。該項目的目的是幫助開發(fā)者更容易的創(chuàng)建基于 Spring 的應用程序和服務谊囚,讓更多人的人更快的對 Spring 進行入門體驗纱皆,為 Spring 生態(tài)系統(tǒng)提供了一種固定的募壕、約定優(yōu)于配置風格的框架。
Spring Boot 具有如下特性:
(1)為基于 Spring 的開發(fā)提供更快的入門體驗
(2)開箱即用纺非,沒有代碼生成哑了,也無需 XML 配置。同時也可以修改默認值來滿足特定的需求烧颖。
(3)提供了一些大型項目中常見的非功能性特性弱左,如嵌入式服務器、安全炕淮、指標拆火,健康檢測、外部配置等涂圆。
(4)Spring Boot 并不是不對 Spring 功能上的增強们镜,而是提供了一種快速使用 Spring 的方式。
2. SpringBoot基礎操作
2.1. SpringBoot入門工程
使用 Intellij IDEA 來新建一個 Spring Boot 項目乘综,打開 IDEA -> New Project -> Spring Initializr憎账。
填寫項目信息:
選擇 Spring Boot 版本及 Web 開發(fā)所需的依賴
創(chuàng)建完成后的工程目錄結構如下:
- .gitignore:Git 過濾配置文件
- pom.xml:Maven 的依賴管理配置文件
- SpringbootdemoApplication.java:程序入口
- resources:資源文件目錄
- static: 靜態(tài)資源文件目錄
- templates:模板資源文件目錄
- application.properties:Spring Boot 的配置文件套硼,實際開發(fā)中會替換成 YAML 語言配置(application.yml)
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.demon</groupId>
<artifactId>springbootdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbootdemo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- parent:繼承了 Spring Boot 的 Parent卡辰,表示我們是一個 Spring Boot 工程
-
spring-boot-starter-web
:包含了spring-boot-starter
還自動幫我們開啟了 Web 支持
功能演示
創(chuàng)建一個 Controller 來演示一下 Spring Boot
package com.funtl.hello.spring.boot.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping(value = "", method = RequestMethod.GET)
public String sayHi() {
return "Hello Spring Boot";
}
}
啟動 SpringbootdemoApplication
的 main()
方法,瀏覽器訪問 http://localhost:8080 可以看到:
Hello Spring Boot
2.2. 單元測試
主要是通過 @RunWith 和 @SpringBootTest 注解來開啟單元測試功能
package com.funtl.hello.spring.boot;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.URL;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HelloSpringBootApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloSpringBootApplicationTests {
@LocalServerPort
private int port;
private URL base;
@Autowired
private TestRestTemplate template;
@Before
public void setUp() throws Exception {
this.base = new URL("http://localhost:" + port + "/");
}
@Test
public void contextLoads() {
ResponseEntity<String> response = template.getForEntity(base.toString(), String.class);
assertThat(response.getBody(), equalTo("Hello Spring Boot"));
}
}
運行它會先啟動 Spring Boot 工程,再啟動單元測試
2.3. 常用配置
2.3.1. 修改tomcat啟動端口
在src/main/resources下修改application.properties或者application.yml文件
#application.yml修改如下
server:
port: 9090
#application.properties修改如下
server.port=8088
重新運行引導類九妈,輸入訪問地址進行訪問反砌。
2.3.2. 讀取配置文件信息
在src/main/resources下的application.properties 增加配置
info=這是一個測試文本
在類中讀取這個配置信息,修改HelloWorldController
@Autowired
private Environment env;
@RequestMapping("/info")
public String info(){
return "HelloWorld~~"+env.getProperty("info");
}
2.3.3 熱部署
在開發(fā)中反復修改類萌朱、頁面等資源宴树,每次修改后都是需要重新啟動才生效,這樣每次啟動都很麻煩晶疼,浪費了大量的時間酒贬,能不能在修改代碼后不重啟就能生效呢?可以翠霍,在pom.xml中添加如下配置就可以實現(xiàn)這樣的功能锭吨,這個過程稱之為熱部署。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
2.3.4 自定義 Banner
在 Spring Boot 啟動的時候會有一個默認的啟動圖案
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.7.RELEASE)
在 src/main/resources
目錄下新建一個 banner.txt
通過 http://patorjk.com/software/taag 網(wǎng)站生成字符串寒匙,將網(wǎng)站生成的字符復制到 banner.txt 中
再次運行這個程序
${AnsiColor.BRIGHT_RED}
////////////////////////////////////////////////////////////////////
// _ooOoo_ //
// o8888888o //
// 88" . "88 //
// (| ^_^ |) //
// O\ = /O //
// ____/`---'\____ //
// .' \\| |// `. //
// / \\||| : |||// \ //
// / _||||| -:- |||||- \ //
// | | \\\ - /// | | //
// | \_| ''\---/'' | | //
// \ .-\__ `-` ___/-. / //
// ___`. .' /--.--\ `. . ___ //
// ."" '< `.___\_<|>_/___.' >'"". //
// | | : `- \`.;`\ _ /`;.`/ - ` : | | //
// \ \ `-. \_ __\ /__ _/ .-` / / //
// ========`-.____`-.___\_____/___.-`____.-'======== //
// `=---=' //
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //
// 佛祖保佑 永不宕機 永無BUG //
////////////////////////////////////////////////////////////////////
常用屬性設置:
-
${AnsiColor.BRIGHT_RED}
:設置控制臺中輸出內容的顏色 -
${application.version}
:用來獲取MANIFEST.MF
文件中的版本號 -
${application.formatted-version}
:格式化后的${application.version}
版本信息 -
${spring-boot.version}
:Spring Boot 的版本號 -
${spring-boot.formatted-version}
:格式化后的${spring-boot.version}
版本信息
2.3.5 關閉特定的自動配置
關閉特定的自動配置使用 @SpringBootApplication 注解的 exclude 參數(shù)即可零如,這里以關閉數(shù)據(jù)源的自動配置為例
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
3. SpringBoot相關服務整合
3.1. 使用內嵌服務
(1)在pom.xml中引入ActiveMQ起步依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
(2)創(chuàng)建消息生產(chǎn)者
/**
* 消息生產(chǎn)者
* @author Administrator
*/
@RestController
public class QueueController {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@RequestMapping("/send")
public void send(String text){
jmsMessagingTemplate.convertAndSend("springBoot_text", text);
}
}
(3)創(chuàng)建消息消費者
@Component
public class Consumer {
@JmsListener(destination="springBoot_text")
public void readMessage(String text){
System.out.println("接收到消息:"+text);
}
}
測試:啟動服務后,在瀏覽器執(zhí)行:localhost:8088/send.do?text=aaaaa
即可看到控制臺輸出消息提示锄弱。Spring Boot內置了ActiveMQ的服務考蕾,所以不用單獨啟動也可以執(zhí)行應用程序。
3.2. 使用外部服務
在src/main/resources下的application.properties增加配置, 指定ActiveMQ的地址
spring.activemq.broker-url=tcp://192.168.25.129:61616
3.3. 發(fā)送Map信息
(1)修改QueueController.java
@RequestMapping("/sendmap")
public void sendMap(){
Map map=new HashMap<>();
map.put("mobile", "13900001111");
map.put("content", "恭喜獲得10元代金券");
jmsMessagingTemplate.convertAndSend("springBoot_map",map);
}
(2)修改Consumer.java
@JmsListener(destination="springBoot_map")
public void readMap(Map map){
System.out.println(map);
}
文檔下載地址:
https://wenku.baidu.com/view/7443f6d853d380eb6294dd88d0d233d4b14e3fa5