重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
SpringBoot如何进行配置与使用?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
创新互联是一家集网站建设,信阳企业网站建设,信阳品牌网站建设,网站定制,信阳网站建设报价,网络营销,网络优化,信阳网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。
简介
Spring 框架是非常著名的 Java 开源框架,历经十多年的发展,整个生态系统已经非常完善甚至是繁杂,Spring Boot 正是为了解决这个问题而开发的,为 Spring 平台和第三方库提供了开箱即用的设置,只需要很少的配置就可以开始一个 Spring 项目。当然,建议使用 Java 8 来进行开发。
Spring Boot 实际上走的是 Servlet 的路线,所以需要一个 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 的强大威力了!创建一个名为 app.groovy 的文件
@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 关掉,具体的步骤是
# 查找对应的进程号 ps aux | grep nginx # 发送关闭信号 kill -QUIT [nginx 主进程 pid]
解决掉各种拦路虎,我们再次运行 springj run app.groovy ,就可以在浏览器中见到 Hello World 了。
dawang$ springj run app.groovy Resolving dependencies....... . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.3.6.RELEASE)
最后我们需要安装的有Gradle 和 IntelliJ IDEA CE ,这里就不赘述了,安装好了我们就可以进行下一步了
Hello World
在 Spring INITIALIZR 进行简单设置即可生成项目模板,如下图所示:
然后我们把下载的文件解压并导入 IntelliJ 中,稍作等待即可。
目录结构如上图所示,我们直接运行这个 main 函数看看,控制台中的输出为
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: 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 ,其中只包含了两个模块:
dependencies { compile('org.springframework.boot:spring-boot-starter') testCompile('org.springframework.boot:spring-boot-starter-test') }
其中:
我们加入 spring-boot-starter-web 模块,对应的 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 这个 package 中加入一个 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."; } }
再启动主程序,访问 localhost:8080/hello 时就可以看到结果了:
然后我们编写一下对应的测试 HellowordApplicationTests (单词拼错了不要在意这些细节),注意需要引入一些 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."))); } }
具体测试简单来说就是使用 MockServletContext 来创建一个新的 WebApplicationContext ,然后我们就可以模拟访问 localhost:8080/hello 了,运行该测试,可以发现一切正常。
至此,我们就了解了如何开始一个 Spring Boot 项目,并编写了一个简单的路由用来显示对应内容。接下来我们会更多介绍开发相关的其他知识。
Starter POMs
简单来说,Starter POMs 是方便我们快速给应用添加功能的,只需要在 build.gradle 中包含对应的 starter,可以省去大量的配置和依赖管理,下面是一些常用的 starter
如果想要切换容器和日志系统可以用下面的包
更多社区贡献的 starter POMs 可以在 这里 查阅。
组织代码最佳实践
不要使用 default package ,建议使用反转的域名来命名包
把 main 应用类放在 root package 中,其他的类放在子包中,结构如下所示
wdx +- helloworld +- HelloworldApplication.java <- main class | +- web | +- HelloController.java | +- service | +- CustomerService.java
打包运行
我们在终端中执行 gradle assemble 可以生成一个 jar 包,也可以直接执行这个 jar 包来启动整个应用,如
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> 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 包会比较大。如果想要开启远程调试,命令为
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 中进行配置,比如:
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 即可。
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联行业资讯频道,感谢您对创新互联的支持。