Spring Boot 快速入門指南
最近因?yàn)轫?xiàng)目的緣故,需要接觸 Spring Boot,詳細(xì)的介紹可以參考官方的文檔,這里主要根據(jù)自己學(xué)習(xí)的實(shí)踐進(jìn)行簡單分享。版本:1.3.6
簡介
Spring 框架是非常著名的 Java 開源框架,歷經(jīng)十多年的發(fā)展,整個(gè)生態(tài)系統(tǒng)已經(jīng)非常完善甚至是繁雜,Spring Boot 正是為了解決這個(gè)問題而開發(fā)的,為 Spring 平臺(tái)和第三方庫提供了開箱即用的設(shè)置,只需要很少的配置就可以開始一個(gè) Spring 項(xiàng)目。當(dāng)然,建議使用 Java 8 來進(jìn)行開發(fā)。
Spring Boot 實(shí)際上走的是 Servlet 的路線,所以需要一個(gè) Servlet 容器,什么 Tomcat/Jetty 都支持,比較意外的是居然還支持 Undertow(Undertow 大法好)。
安裝
簡單粗暴直接上命令行,具體的簡介參考注釋
# 確定 Java 版本 dawang:~ dawang$ java -version java version "1.8.0_91" Java(TM) SE Runtime Environment (build 1.8.0_91-b14) Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode) # 安裝 Spring Boot CLI # 這是第一條語句 dawang:~ dawang$ brew tap pivotal/tap ==> Tapping pivotal/tap Cloning into '/usr/local/Library/Taps/pivotal/homebrew-tap'... remote: Counting objects: 16, done. remote: Compressing objects: 100% (14/14), done. remote: Total 16 (delta 2), reused 5 (delta 0), pack-reused 0 Unpacking objects: 100% (16/16), done. Checking connectivity... done. Tapped 9 formulae (50 files, 46.1K) # 這是第二條語句 dawang:~ dawang$ brew install springboot ==> Installing springboot from pivotal/tap ==> Downloading https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/1.3.6.RELEASE/spring-boot-cli-1.3.6.RELEASE-bin.tar. ######################################################################## 100.0% ==> Caveats Bash completion has been installed to: /usr/local/etc/bash_completion.d zsh completion has been installed to: /usr/local/share/zsh/site-functions ==> Summary :beer: /usr/local/Cellar/springboot/1.3.6.RELEASE: 6 files, 8.9M, built in 4 minutes 39 seconds
然后我們就可以試試看 Spring CLI 的強(qiáng)大威力了!創(chuàng)建一個(gè)名為 app.groovy 的文件
@RestController
class ThisWillActuallyRun {
@RequestMapping("/")
String home() {
"Hello World"
}
}
只需要運(yùn)行 spring run app.groovy 即可!然而,在我的機(jī)器上并沒有這么順利, spring 已經(jīng)被 ruby 無情占用,只好在 .bashrc 中新建一個(gè)別名 alias springj="/usr/local/Cellar/springboot/1.3.6.RELEASE/bin/spring" ,然后用 springj run app.groovy 運(yùn)行。
還不行!打開 localhost:8080 的時(shí)候發(fā)現(xiàn)機(jī)器啟動(dòng)著 nginx,所以要先把 nginx 關(guān)掉,具體的步驟是
# 查找對(duì)應(yīng)的進(jìn)程號(hào) ps aux | grep nginx # 發(fā)送關(guān)閉信號(hào) kill -QUIT [nginx 主進(jìn)程 pid]
解決掉各種攔路虎,我們?cè)俅芜\(yùn)行 springj run app.groovy ,就可以在瀏覽器中見到 Hello World 了。
dawang$ springj run app.groovy Resolving dependencies....... . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.3.6.RELEASE)
最后我們需要安裝的有Gradle 和 IntelliJ IDEA CE ,這里就不贅述了,安裝好了我們就可以進(jìn)行下一步了
Hello World
在 Spring INITIALIZR 進(jìn)行簡單設(shè)置即可生成項(xiàng)目模板,如下圖所示:
然后我們把下載的文件解壓并導(dǎo)入 IntelliJ 中,稍作等待即可。
目錄結(jié)構(gòu)如上圖所示,我們直接運(yùn)行這個(gè) main 函數(shù)看看,控制臺(tái)中的輸出為
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.3.6.RELEASE) 2016-07-19 19:29:41.235 INFO 65812 --- [ main] wdx.helloworld.HellowordApplication : Starting HellowordApplication on dawang.local with PID 65812 (/Users/dawang/Documents/DJI/Code/helloword/build/classes/main started by dawang in /Users/dawang/Documents/DJI/Code/helloword) 2016-07-19 19:29:41.239 INFO 65812 --- [ main] wdx.helloworld.HellowordApplication : No active profile set, falling back to default profiles: default 2016-07-19 19:29:41.320 INFO 65812 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@545997b1: startup date [Tue Jul 19 19:29:41 CST 2016]; root of context hierarchy 2016-07-19 19:29:42.336 INFO 65812 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2016-07-19 19:29:42.353 INFO 65812 --- [ main] wdx.helloworld.HellowordApplication : Started HellowordApplication in 1.865 seconds (JVM running for 3.141) 2016-07-19 19:29:42.354 INFO 65812 --- [ Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@545997b1: startup date [Tue Jul 19 19:29:41 CST 2016]; root of context hierarchy 2016-07-19 19:29:42.356 INFO 65812 --- [ Thread-1] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown Process finished with exit code 0
當(dāng)然,因?yàn)槲覀兊某绦蛑袥]有做任何操作,也沒有配合 Web 模塊,所以加載 Spring 完成之后就結(jié)束了。
我們看看項(xiàng)目對(duì)應(yīng)的 build.gradle ,其中只包含了兩個(gè)模塊:
dependencies {
compile('org.springframework.boot:spring-boot-starter')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
其中:
- spring-boot-starter :核心模塊,包括自動(dòng)配置支持、日志和 YAML
- spring-boot-starter-test :測(cè)試模塊,包括 JUnit、Hamcrest、Mockito
我們加入 spring-boot-starter-web 模塊,對(duì)應(yīng)的 dependencies 部分為
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
然后在 wdx.helloworld.web 這個(gè) package 中加入一個(gè) HelloController 類:
package wdx.helloworld.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by dawang on 16/7/20.
*/
@RestController
public class HelloController {
@RequestMapping("/hello")
public String index() {
return "Hello World! This is wdxtub.";
}
}
再啟動(dòng)主程序,訪問 localhost:8080/hello 時(shí)就可以看到結(jié)果了:
然后我們編寫一下對(duì)應(yīng)的測(cè)試 HellowordApplicationTests (單詞拼錯(cuò)了不要在意這些細(xì)節(jié)),注意需要引入一些 static 方法:
package wdx.helloworld;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import wdx.helloworld.web.HelloController;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.hamcrest.Matchers.equalTo;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockServletContext.class)
@WebAppConfiguration
public class HellowordApplicationTests {
private MockMvc mvc;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
}
@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello World! This is wdxtub.")));
}
}
具體測(cè)試簡單來說就是使用 MockServletContext 來創(chuàng)建一個(gè)新的 WebApplicationContext ,然后我們就可以模擬訪問 localhost:8080/hello 了,運(yùn)行該測(cè)試,可以發(fā)現(xiàn)一切正常。
至此,我們就了解了如何開始一個(gè) Spring Boot 項(xiàng)目,并編寫了一個(gè)簡單的路由用來顯示對(duì)應(yīng)內(nèi)容。接下來我們會(huì)更多介紹開發(fā)相關(guān)的其他知識(shí)。
Starter POMs
簡單來說,Starter POMs 是方便我們快速給應(yīng)用添加功能的,只需要在 build.gradle 中包含對(duì)應(yīng)的 starter,可以省去大量的配置和依賴管理,下面是一些常用的 starter
- spring-boot-starter : 核心 Spring Boot starter,包括自動(dòng)配置支持,日志和 YAML
- spring-boot-starter-actuator : 監(jiān)控和管理應(yīng)用
- spring-boot-starter-remote-shell : 添加遠(yuǎn)程 ssh shell 支持
- spring-boot-starter-amqp : 高級(jí)消息隊(duì)列協(xié)議,通過 spring-rabbit 實(shí)現(xiàn)
- spring-boot-starter-cloud-connectors : 簡化在云平臺(tái)下服務(wù)的連接
- spring-boot-starter-elasticsearch : 對(duì) Elasticsearch 搜索和分析引擎的支持
- spring-boot-starter-data-jpa : 對(duì) Java 持久化 API 的支持,包括 spring-data-jpa , spring-orm 和 Hibernate
- spring-boot-starter-data-mongodb : 對(duì) MongoDB 的支持
- spring-boot-starter-mail : 對(duì) javax.mail 的支持
- spring-boot-starter-mobile : 對(duì) spring-mobile 的支持
- spring-boot-starter-redis : 對(duì) Redis 的支持
- spring-boot-starter-security : 對(duì) spring-security 的支持
- spring-boot-starter-test : 對(duì)常用測(cè)試依賴的支持,包括 JUnit, Hamcrest 和 Mockito,還有 spring-test 模塊
- spring-boot-starter-web : 對(duì)全棧 web 開發(fā)的支持,包括 Tomcat 和 spring-webmvc
- spring-boot-starter-websocket : 對(duì) WebSocket 開發(fā)的支持
- spring-boot-starter-ws : 對(duì) Spring Web Service 的支持
如果想要切換容器和日志系統(tǒng)可以用下面的包
- spring-boot-starter-jetty : 導(dǎo)入 Jetty HTTP 引擎
- spring-boot-starter-log4j : 對(duì) Log4J 日志系統(tǒng)的支持
- spring-boot-starter-logging : 導(dǎo)入 Spring Boot 的默認(rèn)日志系統(tǒng)
- spring-boot-starter-tomcat : 導(dǎo)入 Spring Boot 的默認(rèn) HTTP 引擎
- spring-boot-starter-undertow : 導(dǎo)入 Undertow HTTP 引擎
更多社區(qū)貢獻(xiàn)的 starter POMs 可以在 這里 查閱。
組織代碼最佳實(shí)踐
不要使用 default package ,建議使用反轉(zhuǎn)的域名來命名包
把 main 應(yīng)用類放在 root package 中,其他的類放在子包中,結(jié)構(gòu)如下所示
wdx +- helloworld +- HelloworldApplication.java <- main class | +- web | +- HelloController.java | +- service | +- CustomerService.java
- Spring Boot 提倡在代碼中進(jìn)行配置。通常定義了 main 方法的類是使用 @Configuration 注解的好地方
- 不需要將所有的 @Configufation 放進(jìn)一個(gè)單獨(dú)的類中,可以使用 @Import 注解可以導(dǎo)入其他的配置類。也可以用 @ComponentScan 注解自動(dòng)收集所有的組件,包括 @Configuration 類
- 如果要使用基于 XML 的配置,也最好從 @Configuration 類開始,然后使用 @ImportResource 注解來加載 XML 配置文件
- Spring Boot 另一個(gè)很好的特性是會(huì)根據(jù)所添加的 jar 依賴來配置 Spring 應(yīng)用,只需要簡單把 @EnableAutoConfiguration 加入到 @Configuration 類即可
- SpringBootApplication 注解默認(rèn)等價(jià)于 @Configuration , @EnableAutoConfiguration 和 ComponentScan 這三個(gè)加起來的效果。
打包運(yùn)行
我們?cè)诮K端中執(zhí)行 gradle assemble 可以生成一個(gè) jar 包,也可以直接執(zhí)行這個(gè) jar 包來啟動(dòng)整個(gè)應(yīng)用,如
dawang:helloword dawang$ java -jar build/libs/helloword-0.0.1-SNAPSHOT.jar
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.3.6.RELEASE)
2016-07-20 13:11:01.859 INFO 36943 --- [ main] wdx.helloworld.HellowordApplication : Starting HellowordApplication on dawang.local with PID 36943 (/Users/dawang/Documents/DJI/Code/helloword/build/libs/helloword-0.0.1-SNAPSHOT.jar started by dawang in /Users/dawang/Documents/DJI/Code/helloword)
2016-07-20 13:11:01.864 INFO 36943 --- [ main] wdx.helloworld.HellowordApplication : No active profile set, falling back to default profiles: default
2016-07-20 13:11:01.960 INFO 36943 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@67424e82: startup date [Wed Jul 20 13:11:01 CST 2016]; root of context hierarchy
2016-07-20 13:11:03.727 INFO 36943 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-07-20 13:11:03.750 INFO 36943 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2016-07-20 13:11:03.752 INFO 36943 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.36
2016-07-20 13:11:03.897 INFO 36943 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2016-07-20 13:11:03.897 INFO 36943 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1943 ms
2016-07-20 13:11:04.275 INFO 36943 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2016-07-20 13:11:04.282 INFO 36943 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-07-20 13:11:04.283 INFO 36943 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-07-20 13:11:04.283 INFO 36943 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-07-20 13:11:04.284 INFO 36943 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2016-07-20 13:11:04.658 INFO 36943 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@67424e82: startup date [Wed Jul 20 13:11:01 CST 2016]; root of context hierarchy
2016-07-20 13:11:04.751 INFO 36943 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello]}" onto public java.lang.String wdx.helloworld.web.HelloController.index()
2016-07-20 13:11:04.755 INFO 36943 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-07-20 13:11:04.755 INFO 36943 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-07-20 13:11:04.810 INFO 36943 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-07-20 13:11:04.810 INFO 36943 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-07-20 13:11:04.875 INFO 36943 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-07-20 13:11:05.028 INFO 36943 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-07-20 13:11:05.145 INFO 36943 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-07-20 13:11:05.151 INFO 36943 --- [ main] wdx.helloworld.HellowordApplication : Started HellowordApplication in 4.0 seconds (JVM running for 4.484)
當(dāng)然,因?yàn)樾枰械囊蕾嚕麄€(gè) jar 包會(huì)比較大。如果想要開啟遠(yuǎn)程調(diào)試,命令為
java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n -jar build/libs/helloword-0.0.1-SNAPSHOT.jar
Gradle 運(yùn)行
當(dāng)然我們也可以簡單使用內(nèi)置的 Gradle 腳本來運(yùn)行,直接 gradle bootRun 即可。
配置 Undertow
如果想要用 Undertow 來替換默認(rèn)的 Tomcat,也可以簡單在 build.gradle 中進(jìn)行配置,比如:
configurations {
compile.exclude module: "spring-boot-starter-tomcat"
}
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-undertow')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
然后使用 gradle bootRun 即可。
以上所述是小編給大家介紹的Spring Boot 快速入門指南,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
JDK21新特性Record?Patterns記錄模式詳解(最新推薦)
這篇文章主要介紹了JDK21新特性Record?Patterns記錄模式詳解,本JEP建立在Pattern?Matching?for?instanceof(JEP?394)的基礎(chǔ)上,該功能已在JDK?16中發(fā)布,它與Pattern?Matching?for?switch(JEP?441)共同演進(jìn),需要的朋友可以參考下2023-09-09
Java利用遞歸實(shí)現(xiàn)樹形結(jié)構(gòu)的工具類
有時(shí)候,我們的數(shù)據(jù)是帶有層級(jí)的,比如常見的省市區(qū)三級(jí)聯(lián)動(dòng),就是一層套著一層。而我們?cè)跀?shù)據(jù)庫存放數(shù)據(jù)的時(shí)候,往往是列表形式的,這個(gè)時(shí)候可能就需要遞歸處理為樹形結(jié)構(gòu)了。本文就為大家介紹了Java利用遞歸實(shí)現(xiàn)樹形結(jié)構(gòu)的工具類,希望對(duì)大家有所幫助2023-03-03
SpringBoot2.x入門教程之引入jdbc模塊與JdbcTemplate簡單使用方法
這篇文章主要介紹了SpringBoot2.x入門教程之引入jdbc模塊與JdbcTemplate簡單使用方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
Java關(guān)鍵字final、static使用總結(jié)
final方法不能被子類的方法覆蓋,但可以被繼承。用static修飾的代碼塊表示靜態(tài)代碼塊,當(dāng)Java虛擬機(jī)(JVM)加載類時(shí),就會(huì)執(zhí)行該代碼塊,下面通過本文給大家分享Java關(guān)鍵字final、static使用總結(jié),感興趣的朋友一起看看吧2017-07-07
Java提示解析時(shí)已到達(dá)文件結(jié)尾的解決方法
在本篇文章中小編給大家分享了關(guān)于Java提示解析時(shí)已到達(dá)文件結(jié)尾的解決方法,需要的朋友們學(xué)習(xí)下。2019-07-07

