使用Spring Boot创建一个应用
本文主要演示如何使用Spring Boot加速应用开发的。你可以访问Spring Initializr,快速构建属于你自己的基于Spring Boot的应用。
如图,一键即可生成项目。
1.开始构建项目
1.1)项目结构
1.2 pom.xml
<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="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.0http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.springframework</groupId><artifactId>gs-spring-boot</artifactId><version>0.1.0</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.3.5.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><properties><java.version>1.8</java.version></properties><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
Spring Boot Maven plugin提供以下支持:
1.收集classpath下的jar,作为单个可运行的“über-jar”,这样可以更适合传输和执行。
2.搜索public static void main(),标记为可运行的class
3.提供内置依赖管理(Spring Boot dependencies.)
1.3 使用spring boot能做什么?
它提供快速构建应用的方式,搜索classpath和配置的bean,可以帮你从基础工作冲解脱出来,专心实现业务。
1.使用springmvc?提供了几个bean,spring会自动加入;spring需要servlet容器支持,spring自动配置内嵌的tomcat。
2.使用 jetty?不想使用tomcat,spring很容易进行切换
3.Thymeleaf?也提供了支持。Thymeleaf 如果在classpath下,spring会自动加入SpringTemplateEngine
这仅仅是几个自动配置的场景。
spring boot不会生成代码或修改你的文件,它会动态扩展bean和配置,并在应用中使用他们。
1.4 创建一个简单的web应用
packagehello;importorg.springframework.web.bind.annotation.RestController;importorg.springframework.web.bind.annotation.RequestMapping;@RestControllerpublicclassHelloController{@RequestMapping("/")publicStringindex(){return"GreetingsfromSpringBoot!";}}
@RestController表示类准备使用SpringMVC处理web请求,绑定了@Controller和@ResponseBody
packageorg.springframework.web.bind.annotation;@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE})@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)@java.lang.annotation.Documented@org.springframework.stereotype.Controller@org.springframework.web.bind.annotation.ResponseBodypublic@interfaceRestController{java.lang.Stringvalue()default"";}
1.5创建一个应用Class
packagehello;importjava.util.Arrays;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.context.ApplicationContext;@SpringBootApplicationpublicclassApplication{publicstaticvoidmain(String[]args){ApplicationContextctx=SpringApplication.run(Application.class,args);System.out.println("Let'sinspectthebeansprovidedbySpringBoot:");String[]beanNames=ctx.getBeanDefinitionNames();Arrays.sort(beanNames);for(StringbeanName:beanNames){System.out.println(beanName);}}}
@SpringBootApplication 也是1个组合体
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@Configuration@EnableAutoConfiguration@ComponentScanpublic@interfaceSpringBootApplication{...}
@ComponentScan:告诉spring boot查找其他的components,configurations,services
@EnableAutoConfiguration :告诉spring boot基于classpath添加bean,settings。
一般情况下,你需要添加@EnableWebMvc,但spring boot在classpath中发现spring-webmvc
,会自动添加@EnableWebMvc;
SpringApplication.run() 启动应用入口,没有web.xml,没有application.xml.100%的java.
输出结果如下
D:\Java\jdk1.7.0_65\bin\java-Didea.launcher.port=7535"-Didea.launcher.bin.path=D:\ProgramFiles(x86)\JetBrains\IntelliJIDEA14.1.4\bin"-Dfile.encoding=UTF-8-classpath"D:\Java\jdk1.7.0_65\jre\lib\charsets.jar;D:\Java\jdk1.7.0_65\jre\lib\deploy.jar;D:\Java\jdk1.7.0_65\jre\lib\javaws.jar;D:\Java\jdk1.7.0_65\jre\lib\jce.jar;D:\Java\jdk1.7.0_65\jre\lib\jfr.jar;D:\Java\jdk1.7.0_65\jre\lib\jfxrt.jar;D:\Java\jdk1.7.0_65\jre\lib\jsse.jar;D:\Java\jdk1.7.0_65\jre\lib\management-agent.jar;D:\Java\jdk1.7.0_65\jre\lib\plugin.jar;D:\Java\jdk1.7.0_65\jre\lib\resources.jar;D:\Java\jdk1.7.0_65\jre\lib\rt.jar;D:\Java\jdk1.7.0_65\jre\lib\ext\access-bridge-64.jar;D:\Java\jdk1.7.0_65\jre\lib\ext\dnsns.jar;D:\Java\jdk1.7.0_65\jre\lib\ext\jaccess.jar;D:\Java\jdk1.7.0_65\jre\lib\ext\localedata.jar;D:\Java\jdk1.7.0_65\jre\lib\ext\sunec.jar;D:\Java\jdk1.7.0_65\jre\lib\ext\sunjce_provider.jar;D:\Java\jdk1.7.0_65\jre\lib\ext\sunmscapi.jar;D:\Java\jdk1.7.0_65\jre\lib\ext\zipfs.jar;E:\open\apache\spring-boot-example\target\classes;D:\Documents\.m2\repository\org\thymeleaf\thymeleaf\2.1.4.RELEASE\thymeleaf-2.1.4.RELEASE.jar;D:\Documents\.m2\repository\ognl\ognl\3.0.8\ognl-3.0.8.jar;D:\Documents\.m2\repository\org\javassist\javassist\3.18.1-GA\javassist-3.18.1-GA.jar;D:\Documents\.m2\repository\org\unbescape\unbescape\1.1.0.RELEASE\unbescape-1.1.0.RELEASE.jar;D:\Documents\.m2\repository\org\slf4j\slf4j-api\1.7.21\slf4j-api-1.7.21.jar;D:\Documents\.m2\repository\org\springframework\boot\spring-boot-starter-web\1.3.5.RELEASE\spring-boot-starter-web-1.3.5.RELEASE.jar;D:\Documents\.m2\repository\org\springframework\boot\spring-boot-starter\1.3.5.RELEASE\spring-boot-starter-1.3.5.RELEASE.jar;D:\Documents\.m2\repository\org\springframework\boot\spring-boot\1.3.5.RELEASE\spring-boot-1.3.5.RELEASE.jar;D:\Documents\.m2\repository\org\springframework\spring-core\4.2.6.RELEASE\spring-core-4.2.6.RELEASE.jar;D:\Documents\.m2\repository\org\springframework\spring-context\4.2.6.RELEASE\spring-context-4.2.6.RELEASE.jar;D:\Documents\.m2\repository\org\springframework\spring-aop\4.2.6.RELEASE\spring-aop-4.2.6.RELEASE.jar;D:\Documents\.m2\repository\aopalliance\aopalliance\1.0\aopalliance-1.0.jar;D:\Documents\.m2\repository\org\springframework\spring-beans\4.2.6.RELEASE\spring-beans-4.2.6.RELEASE.jar;D:\Documents\.m2\repository\org\springframework\spring-expression\4.2.6.RELEASE\spring-expression-4.2.6.RELEASE.jar;D:\Documents\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\1.3.5.RELEASE\spring-boot-autoconfigure-1.3.5.RELEASE.jar;D:\Documents\.m2\repository\org\springframework\boot\spring-boot-starter-logging\1.3.5.RELEASE\spring-boot-starter-logging-1.3.5.RELEASE.jar;D:\Documents\.m2\repository\ch\qos\logback\logback-classic\1.1.7\logback-classic-1.1.7.jar;D:\Documents\.m2\repository\ch\qos\logback\logback-core\1.1.7\logback-core-1.1.7.jar;D:\Documents\.m2\repository\org\slf4j\jcl-over-slf4j\1.7.21\jcl-over-slf4j-1.7.21.jar;D:\Documents\.m2\repository\org\slf4j\jul-to-slf4j\1.7.21\jul-to-slf4j-1.7.21.jar;D:\Documents\.m2\repository\org\slf4j\log4j-over-slf4j\1.7.21\log4j-over-slf4j-1.7.21.jar;D:\Documents\.m2\repository\org\yaml\snakeyaml\1.16\snakeyaml-1.16.jar;D:\Documents\.m2\repository\org\springframework\boot\spring-boot-starter-tomcat\1.3.5.RELEASE\spring-boot-starter-tomcat-1.3.5.RELEASE.jar;D:\Documents\.m2\repository\org\apache\tomcat\embed\tomcat-embed-core\8.0.33\tomcat-embed-core-8.0.33.jar;D:\Documents\.m2\repository\org\apache\tomcat\embed\tomcat-embed-el\8.0.33\tomcat-embed-el-8.0.33.jar;D:\Documents\.m2\repository\org\apache\tomcat\embed\tomcat-embed-logging-juli\8.0.33\tomcat-embed-logging-juli-8.0.33.jar;D:\Documents\.m2\repository\org\apache\tomcat\embed\tomcat-embed-websocket\8.0.33\tomcat-embed-websocket-8.0.33.jar;D:\Documents\.m2\repository\org\springframework\boot\spring-boot-starter-validation\1.3.5.RELEASE\spring-boot-starter-validation-1.3.5.RELEASE.jar;D:\Documents\.m2\repository\org\hibernate\hibernate-validator\5.2.4.Final\hibernate-validator-5.2.4.Final.jar;D:\Documents\.m2\repository\javax\validation\validation-api\1.1.0.Final\validation-api-1.1.0.Final.jar;D:\Documents\.m2\repository\org\jboss\logging\jboss-logging\3.3.0.Final\jboss-logging-3.3.0.Final.jar;D:\Documents\.m2\repository\com\fasterxml\classmate\1.1.0\classmate-1.1.0.jar;D:\Documents\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.6.6\jackson-databind-2.6.6.jar;D:\Documents\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.6.6\jackson-annotations-2.6.6.jar;D:\Documents\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.6.6\jackson-core-2.6.6.jar;D:\Documents\.m2\repository\org\springframework\spring-web\4.2.6.RELEASE\spring-web-4.2.6.RELEASE.jar;D:\Documents\.m2\repository\org\springframework\spring-webmvc\4.2.6.RELEASE\spring-webmvc-4.2.6.RELEASE.jar;D:\ProgramFiles(x86)\JetBrains\IntelliJIDEA14.1.4\lib\idea_rt.jar"com.intellij.rt.execution.application.AppMainhello.Application--spring.output.ansi.enabled=always._________/\\/___'_____(_)______\\\\(()\___|'_|'_||'_\/_`|\\\\\\/___)||_)|||||||(_||))))'|____|.__|_||_|_||_\__,|////=========|_|==============|___/=/_/_/_/::SpringBoot::(v1.3.5.RELEASE)2016-06-1919:32:34.189INFO10008---[main]hello.Application:StartingApplicationonzhaoguoyu-pcwithPID10008(E:\open\apache\spring-boot-example\target\classesstartedbyAdministratorinE:\open\apache\spring-boot-example)2016-06-1919:32:34.192INFO10008---[main]hello.Application:Noactiveprofileset,fallingbacktodefaultprofiles:default2016-06-1919:32:34.256INFO10008---[main]ationConfigEmbeddedWebApplicationContext:Refreshingorg.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@12c11e94:startupdate[SunJun1919:32:34CST2016];rootofcontexthierarchy2016-06-1919:32:35.342INFO10008---[main]s.b.c.e.t.TomcatEmbeddedServletContainer:Tomcatinitializedwithport(s):8080(http)2016-06-1919:32:35.353INFO10008---[main]o.apache.catalina.core.StandardService:StartingserviceTomcat2016-06-1919:32:35.354INFO10008---[main]org.apache.catalina.core.StandardEngine:StartingServletEngine:ApacheTomcat/8.0.332016-06-1919:32:35.423INFO10008---[ost-startStop-1]o.a.c.c.C.[Tomcat].[localhost].[/]:InitializingSpringembeddedWebApplicationContext2016-06-1919:32:35.423INFO10008---[ost-startStop-1]o.s.web.context.ContextLoader:RootWebApplicationContext:initializationcompletedin1169ms2016-06-1919:32:35.642INFO10008---[ost-startStop-1]o.s.b.c.e.ServletRegistrationBean:Mappingservlet:'dispatcherServlet'to[/]2016-06-1919:32:35.644INFO10008---[ost-startStop-1]o.s.b.c.embedded.FilterRegistrationBean:Mappingfilter:'characterEncodingFilter'to:[/*]2016-06-1919:32:35.645INFO10008---[ost-startStop-1]o.s.b.c.embedded.FilterRegistrationBean:Mappingfilter:'hiddenHttpMethodFilter'to:[/*]2016-06-1919:32:35.645INFO10008---[ost-startStop-1]o.s.b.c.embedded.FilterRegistrationBean:Mappingfilter:'httpPutFormContentFilter'to:[/*]2016-06-1919:32:35.645INFO10008---[ost-startStop-1]o.s.b.c.embedded.FilterRegistrationBean:Mappingfilter:'requestContextFilter'to:[/*]2016-06-1919:32:35.766INFO10008---[main]s.w.s.m.m.a.RequestMappingHandlerAdapter:Lookingfor@ControllerAdvice:org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@12c11e94:startupdate[SunJun1919:32:34CST2016];rootofcontexthierarchy2016-06-1919:32:35.812INFO10008---[main]s.w.s.m.m.a.RequestMappingHandlerMapping:Mapped"{[/]}"ontopublicjava.lang.Stringhello.HelloController.index()2016-06-1919:32:35.815INFO10008---[main]s.w.s.m.m.a.RequestMappingHandlerMapping:Mapped"{[/error]}"ontopublicorg.springframework.http.ResponseEntity<java.util.Map<java.lang.String,java.lang.Object>>org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)2016-06-1919:32:35.815INFO10008---[main]s.w.s.m.m.a.RequestMappingHandlerMapping:Mapped"{[/error],produces=[text/html]}"ontopublicorg.springframework.web.servlet.ModelAndVieworg.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)2016-06-1919:32:35.836INFO10008---[main]o.s.w.s.handler.SimpleUrlHandlerMapping:MappedURLpath[/webjars/**]ontohandleroftype[classorg.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-06-1919:32:35.836INFO10008---[main]o.s.w.s.handler.SimpleUrlHandlerMapping:MappedURLpath[/**]ontohandleroftype[classorg.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-06-1919:32:35.875INFO10008---[main]o.s.w.s.handler.SimpleUrlHandlerMapping:MappedURLpath[/**/favicon.ico]ontohandleroftype[classorg.springframework.web.servlet.resource.ResourceHttpRequestHandler]2016-06-1919:32:35.965INFO10008---[main]o.s.j.e.a.AnnotationMBeanExporter:RegisteringbeansforJMXexposureonstartup2016-06-1919:32:36.008INFO10008---[main]s.b.c.e.t.TomcatEmbeddedServletContainer:Tomcatstartedonport(s):8080(http)2016-06-1919:32:36.011INFO10008---[main]hello.Application:StartedApplicationin2.168seconds(JVMrunningfor2.426)Let'sinspectthebeansprovidedbySpringBoot:applicationbasicErrorControllerbeanNameHandlerMappingbeanNameViewResolvercharacterEncodingFilterdefaultServletHandlerMappingdefaultViewResolverdispatcherServletdispatcherServletRegistrationduplicateServerPropertiesDetectorembeddedServletContainerCustomizerBeanPostProcessorerrorerrorAttributeserrorPageCustomizerfaviconHandlerMappingfaviconRequestHandlerhandlerExceptionResolverhelloControllerhiddenHttpMethodFilterhttpPutFormContentFilterhttpRequestHandlerAdapterjacksonObjectMapperjacksonObjectMapperBuildermappingJackson2HttpMessageConvertermbeanExportermbeanServermessageConvertersmultipart.CONFIGURATION_PROPERTIESmultipartConfigElementmultipartResolvermvcContentNegotiationManagermvcConversionServicemvcPathMatchermvcResourceUrlProvidermvcUriComponentsContributormvcUrlPathHelpermvcValidatormvcViewResolverobjectNamingStrategyorg.springframework.boot.autoconfigure.AutoConfigurationPackagesorg.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfigurationorg.springframework.boot.autoconfigure.condition.BeanTypeRegistryorg.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfigurationorg.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationorg.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfigurationorg.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfigurationorg.springframework.boot.autoconfigure.jmx.JmxAutoConfigurationorg.springframework.boot.autoconfigure.web.DispatcherServletAutoConfigurationorg.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration$DispatcherServletConfigurationorg.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfigurationorg.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcatorg.springframework.boot.autoconfigure.web.ErrorMvcAutoConfigurationorg.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfigurationorg.springframework.boot.autoconfigure.web.HttpEncodingAutoConfigurationorg.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfigurationorg.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfigurationorg.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfigurationorg.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfigurationorg.springframework.boot.autoconfigure.web.MultipartAutoConfigurationorg.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfigurationorg.springframework.boot.autoconfigure.web.WebMvcAutoConfigurationorg.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfigurationorg.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapterorg.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfigurationorg.springframework.boot.autoconfigure.websocket.WebSocketAutoConfigurationorg.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration$TomcatWebSocketConfigurationorg.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessororg.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.storeorg.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessororg.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessororg.springframework.context.annotation.internalAutowiredAnnotationProcessororg.springframework.context.annotation.internalCommonAnnotationProcessororg.springframework.context.annotation.internalConfigurationAnnotationProcessororg.springframework.context.annotation.internalRequiredAnnotationProcessororg.springframework.context.event.internalEventListenerFactoryorg.springframework.context.event.internalEventListenerProcessorpreserveErrorControllerTargetClassPostProcessorpropertySourcesPlaceholderConfigurerrequestContextFilterrequestMappingHandlerAdapterrequestMappingHandlerMappingresourceHandlerMappingserverPropertiessimpleControllerHandlerAdapterspring.http.encoding.CONFIGURATION_PROPERTIESspring.jackson.CONFIGURATION_PROPERTIESspring.mvc.CONFIGURATION_PROPERTIESspring.resources.CONFIGURATION_PROPERTIESstringHttpMessageConvertertomcatEmbeddedServletContainerFactoryviewControllerHandlerMappingviewResolverwebsocketContainerCustomizer
有好多的默认注入的bean. 这些bean就是spring boot强大功能的支持对象。
你可以通过"tomcat"关键字查找,能找到tomcat的踪迹。可以跟踪源码。
访问http://localhost:8080/
1.6添加测试用例
在前面的pom.xml中添加
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
写一个简单的测试用例(这个是基于mock的方式)
packagehello;importstaticorg.hamcrest.Matchers.equalTo;importstaticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.content;importstaticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.status;importorg.junit.Before;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.boot.test.SpringApplicationConfiguration;importorg.springframework.http.MediaType;importorg.springframework.mock.web.MockServletContext;importorg.springframework.test.context.junit4.SpringJUnit4Cla***unner;importorg.springframework.test.context.web.WebAppConfiguration;importorg.springframework.test.web.servlet.MockMvc;importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;importorg.springframework.test.web.servlet.setup.MockMvcBuilders;@RunWith(SpringJUnit4Cla***unner.class)@SpringApplicationConfiguration(classes=MockServletContext.class)@WebAppConfigurationpublicclassHelloControllerTest{privateMockMvcmvc;@BeforepublicvoidsetUp()throwsException{mvc=MockMvcBuilders.standaloneSetup(newHelloController()).build();}@TestpublicvoidgetHello()throwsException{mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("GreetingsfromSpringBoot!")));}}
MockMvc来自spring-test模块,通过一组合适构造,发送HTTP请求。
另外一个测试用例(full-stack integration test)
packagehello;importstaticorg.hamcrest.Matchers.equalTo;importstaticorg.junit.Assert.assertThat;importjava.net.URL;importorg.junit.Before;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.test.IntegrationTest;importorg.springframework.boot.test.SpringApplicationConfiguration;importorg.springframework.boot.test.TestRestTemplate;importorg.springframework.http.ResponseEntity;importorg.springframework.test.context.junit4.SpringJUnit4Cla***unner;importorg.springframework.test.context.web.WebAppConfiguration;importorg.springframework.web.client.RestTemplate;@RunWith(SpringJUnit4Cla***unner.class)@SpringApplicationConfiguration(classes=Application.class)@WebAppConfiguration@IntegrationTest({"server.port=0"})publicclassHelloControllerIT{@Value("${local.server.port}")privateintport;privateURLbase;privateRestTemplatetemplate;@BeforepublicvoidsetUp()throwsException{this.base=newURL("http://localhost:"+port+"/");template=newTestRestTemplate();}@TestpublicvoidgetHello()throwsException{ResponseEntity<String>response=template.getForEntity(base.toString(),String.class);assertThat(response.getBody(),equalTo("GreetingsfromSpringBoot!"));}}
@IntegrationTest("${server.port=0}") 端口随机确定
@Value("${local.server.port}")端口运行时确定。
1.7添加生产环境支持
需要在pom.xml添加
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>
重启应用,会看到增加了额外的日志
2014-06-0313:23:28.119...:Mapped"{[/error],methods=[],params=[],headers=[],consumes...2014-06-0313:23:28.119...:Mapped"{[/error],methods=[],params=[],headers=[],consumes...2014-06-0313:23:28.136...:MappedURLpath[/**]ontohandleroftype[classorg.spri...2014-06-0313:23:28.136...:MappedURLpath[/webjars/**]ontohandleroftype[class...2014-06-0313:23:28.440...:Mapped"{[/info],methods=[GET],params=[],headers=[],consum...2014-06-0313:23:28.441...:Mapped"{[/autoconfig],methods=[GET],params=[],headers=[],...2014-06-0313:23:28.441...:Mapped"{[/mappings],methods=[GET],params=[],headers=[],co...2014-06-0313:23:28.442...:Mapped"{[/trace],methods=[GET],params=[],headers=[],consu...2014-06-0313:23:28.442...:Mapped"{[/env/{name:.*}],methods=[GET],params=[],headers=...2014-06-0313:23:28.442...:Mapped"{[/env],methods=[GET],params=[],headers=[],consume...2014-06-0313:23:28.443...:Mapped"{[/configprops],methods=[GET],params=[],headers=[]...2014-06-0313:23:28.443...:Mapped"{[/metrics/{name:.*}],methods=[GET],params=[],head...2014-06-0313:23:28.443...:Mapped"{[/metrics],methods=[GET],params=[],headers=[],con...2014-06-0313:23:28.444...:Mapped"{[/health],methods=[GET],params=[],headers=[],cons...2014-06-0313:23:28.444...:Mapped"{[/dump],methods=[GET],params=[],headers=[],consum...2014-06-0313:23:28.445...:Mapped"{[/beans],methods=[GET],params=[],headers=[],consu...
尝试访问:http://localhost:8080/health
还有一些线上排查诊断问题其他功能:
http://localhost:8080/env
http://localhost:8080/metrics
http://localhost:8080/dump(线程)
...
小计:
本文章主要内容来自http://spring.io/guides/gs/spring-boot/。不是翻译文章,加自己的实践说明。
真心佩服spring boot的优雅设置。扩展性,无侵入性都有很好的参照价值。以后有空在学习。
下一步的工作:研读http://docs.spring.io/spring-boot/docs/1.3.5.RELEASE/reference/htmlsingle/
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。