服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Spring Boot 快速入门指南

Spring Boot 快速入门指南

2020-08-29 11:50Java之家 Java教程

Spring 框架是非常著名的 Java 开源框架,历经十多年的发展,整个生态系统已经非常完善甚至是繁杂,Spring Boot 正是为了解决这个问题而开发的,为 Spring 平台和第三方库提供了开箱即用的设置,只需要很少的配置就可以开始一个

最近因为项目的缘故,需要接触 spring boot,详细的介绍可以参考官方的文档,这里主要根据自己学习的实践进行简单分享。版本:1.3.6

简介

spring 框架是非常著名的 java 开源框架,历经十多年的发展,整个生态系统已经非常完善甚至是繁杂,spring boot 正是为了解决这个问题而开发的,为 spring 平台和第三方库提供了开箱即用的设置,只需要很少的配置就可以开始一个 spring 项目。当然,建议使用 java 8 来进行开发。

spring boot 实际上走的是 servlet 的路线,所以需要一个 servlet 容器,什么 tomcat/jetty 都支持,比较意外的是居然还支持 undertow(undertow 大法好)。

安装

简单粗暴直接上命令行,具体的简介参考注释

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 确定 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 的强大威力了!创建一个名为 app.groovy 的文件

?
1
2
3
4
5
6
7
@restcontroller
class thiswillactuallyrun {
 @requestmapping("/")
 string home() {
 "hello world"
 }
}

只需要运行 spring run app.groovy 即可!然而,在我的机器上并没有这么顺利, spring 已经被 ruby 无情占用,只好在 .bashrc 中新建一个别名 alias springj="/usr/local/cellar/springboot/1.3.6.release/bin/spring" ,然后用 springj run app.groovy 运行。

还不行!打开 localhost:8080 的时候发现机器启动着 nginx,所以要先把 nginx 关掉,具体的步骤是

?
1
2
3
4
# 查找对应的进程号
ps aux | grep nginx
# 发送关闭信号
kill -quit [nginx 主进程 pid]

解决掉各种拦路虎,我们再次运行 springj run app.groovy ,就可以在浏览器中见到 hello world 了。

?
1
2
3
4
5
6
7
8
9
dawang$ springj run app.groovy
resolving dependencies.......
 . ____ _ __ _ _
 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
 ' |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: spring boot :: (v1.3.6.release)

最后我们需要安装的有gradle intellij idea ce ,这里就不赘述了,安装好了我们就可以进行下一步了

hello world

spring initializr 进行简单设置即可生成项目模板,如下图所示:

Spring Boot 快速入门指南

然后我们把下载的文件解压并导入 intellij 中,稍作等待即可。

Spring Boot 快速入门指南

目录结构如上图所示,我们直接运行这个 main 函数看看,控制台中的输出为

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
. ____ _ __ _ _
 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
 ' |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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

当然,因为我们的程序中没有做任何操作,也没有配合 web 模块,所以加载 spring 完成之后就结束了。

我们看看项目对应的 build.gradle ,其中只包含了两个模块:

?
1
2
3
4
dependencies {
 compile('org.springframework.boot:spring-boot-starter')
 testcompile('org.springframework.boot:spring-boot-starter-test')
}

其中:

  • spring-boot-starter :核心模块,包括自动配置支持、日志和 yaml
  • spring-boot-starter-test :测试模块,包括 junit、hamcrest、mockito

我们加入 spring-boot-starter-web 模块,对应的 dependencies 部分为

?
1
2
3
4
5
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 这个 package 中加入一个 hellocontroller 类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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.";
 }
}

再启动主程序,访问 localhost:8080/hello 时就可以看到结果了:

Spring Boot 快速入门指南

然后我们编写一下对应的测试 hellowordapplicationtests (单词拼错了不要在意这些细节),注意需要引入一些 static 方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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.")));
 }
}

具体测试简单来说就是使用 mockservletcontext 来创建一个新的 webapplicationcontext ,然后我们就可以模拟访问 localhost:8080/hello 了,运行该测试,可以发现一切正常。

Spring Boot 快速入门指南

至此,我们就了解了如何开始一个 spring boot 项目,并编写了一个简单的路由用来显示对应内容。接下来我们会更多介绍开发相关的其他知识。

starter poms

简单来说,starter poms 是方便我们快速给应用添加功能的,只需要在 build.gradle 中包含对应的 starter,可以省去大量的配置和依赖管理,下面是一些常用的 starter

  • spring-boot-starter : 核心 spring boot starter,包括自动配置支持,日志和 yaml
  • spring-boot-starter-actuator : 监控和管理应用
  • spring-boot-starter-remote-shell : 添加远程 ssh shell 支持
  • spring-boot-starter-amqp : 高级消息队列协议,通过 spring-rabbit 实现
  • spring-boot-starter-cloud-connectors : 简化在云平台下服务的连接
  • spring-boot-starter-elasticsearch : 对 elasticsearch 搜索和分析引擎的支持
  • spring-boot-starter-data-jpa : 对 java 持久化 api 的支持,包括 spring-data-jpa , spring-orm 和 hibernate
  • spring-boot-starter-data-mongodb : 对 mongodb 的支持
  • spring-boot-starter-mail : 对 javax.mail 的支持
  • spring-boot-starter-mobile : 对 spring-mobile 的支持
  • spring-boot-starter-redis : 对 redis 的支持
  • spring-boot-starter-security : 对 spring-security 的支持
  • spring-boot-starter-test : 对常用测试依赖的支持,包括 junit, hamcrest 和 mockito,还有 spring-test 模块
  • spring-boot-starter-web : 对全栈 web 开发的支持,包括 tomcat 和 spring-webmvc
  • spring-boot-starter-websocket : 对 websocket 开发的支持
  • spring-boot-starter-ws : 对 spring web service 的支持

如果想要切换容器和日志系统可以用下面的包

  • spring-boot-starter-jetty : 导入 jetty http 引擎
  • spring-boot-starter-log4j : 对 log4j 日志系统的支持
  • spring-boot-starter-logging : 导入 spring boot 的默认日志系统
  • spring-boot-starter-tomcat : 导入 spring boot 的默认 http 引擎
  • spring-boot-starter-undertow : 导入 undertow http 引擎

更多社区贡献的 starter poms 可以在 这里 查阅。

组织代码最佳实践

不要使用 default package ,建议使用反转的域名来命名包

把 main 应用类放在 root package 中,其他的类放在子包中,结构如下所示

?
1
2
3
4
5
6
7
8
9
wdx
 +- helloworld
 +- helloworldapplication.java <- main class
 |
 +- web
 | +- hellocontroller.java
 |
 +- service
 | +- customerservice.java
  • spring boot 提倡在代码中进行配置。通常定义了 main 方法的类是使用 @configuration 注解的好地方
  • 不需要将所有的 @configufation 放进一个单独的类中,可以使用 @import 注解可以导入其他的配置类。也可以用 @componentscan 注解自动收集所有的组件,包括 @configuration 类
  • 如果要使用基于 xml 的配置,也最好从 @configuration 类开始,然后使用 @importresource 注解来加载 xml 配置文件
  • spring boot 另一个很好的特性是会根据所添加的 jar 依赖来配置 spring 应用,只需要简单把 @enableautoconfiguration 加入到 @configuration 类即可
  • springbootapplication 注解默认等价于 @configuration , @enableautoconfiguration 和 componentscan 这三个加起来的效果。

打包运行

我们在终端中执行 gradle assemble 可以生成一个 jar 包,也可以直接执行这个 jar 包来启动整个应用,如

dawang:helloword dawang$ java -jar build/libs/helloword-0.0.1-snapshot.jar

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
. ____ _ __ _ _
 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
 ' |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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)

当然,因为需要包含所有的依赖,整个 jar 包会比较大。如果想要开启远程调试,命令为

?
1
java -xdebug -xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n -jar build/libs/helloword-0.0.1-snapshot.jar

gradle 运行

当然我们也可以简单使用内置的 gradle 脚本来运行,直接 gradle bootrun 即可。

配置 undertow

如果想要用 undertow 来替换默认的 tomcat,也可以简单在 build.gradle 中进行配置,比如:

?
1
2
3
4
5
6
7
8
9
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 快速入门指南,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://www.tuicool.com/articles/Rr6V7jn

延伸 · 阅读

精彩推荐