您好,登錄后才能下訂單哦!
本文主要演示如何使用Spring Boot加速應(yīng)用開發(fā)的。你可以訪問Spring Initializr,快速構(gòu)建屬于你自己的基于Spring Boot的應(yīng)用。
如圖,一鍵即可生成項(xiàng)目。
1.開始構(gòu)建項(xiàng)目
1.1)項(xiàng)目結(jié)構(gòu)
1.2 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 http://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,作為單個(gè)可運(yùn)行的“über-jar”,這樣可以更適合傳輸和執(zhí)行。
2.搜索public static void main(),標(biāo)記為可運(yùn)行的class
3.提供內(nèi)置依賴管理(Spring Boot dependencies.)
1.3 使用spring boot能做什么?
它提供快速構(gòu)建應(yīng)用的方式,搜索classpath和配置的bean,可以幫你從基礎(chǔ)工作沖解脫出來,專心實(shí)現(xiàn)業(yè)務(wù)。
1.使用springmvc?提供了幾個(gè)bean,spring會自動(dòng)加入;spring需要servlet容器支持,spring自動(dòng)配置內(nèi)嵌的tomcat。
2.使用 jetty?不想使用tomcat,spring很容易進(jìn)行切換
3.Thymeleaf?也提供了支持。Thymeleaf 如果在classpath下,spring會自動(dòng)加入SpringTemplateEngine
這僅僅是幾個(gè)自動(dòng)配置的場景。
spring boot不會生成代碼或修改你的文件,它會動(dòng)態(tài)擴(kuò)展bean和配置,并在應(yīng)用中使用他們。
1.4 創(chuàng)建一個(gè)簡單的web應(yīng)用
package hello; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; @RestController public class HelloController { @RequestMapping("/") public String index() { return "Greetings from Spring Boot!"; } }
@RestController表示類準(zhǔn)備使用SpringMVC處理web請求,綁定了@Controller和@ResponseBody
package org.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.ResponseBody public @interface RestController { java.lang.String value() default ""; }
1.5創(chuàng)建一個(gè)應(yīng)用Class
package hello; import java.util.Arrays; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; @SpringBootApplication public class Application { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(Application.class, args); System.out.println("Let's inspect the beans provided by Spring Boot:"); String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.sort(beanNames); for (String beanName : beanNames) { System.out.println(beanName); } } }
@SpringBootApplication 也是1個(gè)組合體
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Configuration @EnableAutoConfiguration @ComponentScan public @interface SpringBootApplication{ ... }
@ComponentScan:告訴spring boot查找其他的components,configurations,services
@EnableAutoConfiguration :告訴spring boot基于classpath添加bean,settings。
一般情況下,你需要添加@EnableWebMvc,但spring boot在classpath中發(fā)現(xiàn) spring-webmvc
,會自動(dòng)添加@EnableWebMvc;
SpringApplication.run() 啟動(dòng)應(yīng)用入口,沒有web.xml,沒有application.xml.100%的java.
輸出結(jié)果如下
D:\Java\jdk1.7.0_65\bin\java -Didea.launcher.port=7535 "-Didea.launcher.bin.path=D:\Program Files (x86)\JetBrains\IntelliJ IDEA 14.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:\Program Files (x86)\JetBrains\IntelliJ IDEA 14.1.4\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain hello.Application --spring.output.ansi.enabled=always . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.3.5.RELEASE) 2016-06-19 19:32:34.189 INFO 10008 --- [ main] hello.Application : Starting Application on zhaoguoyu-pc with PID 10008 (E:\open\apache\spring-boot-example\target\classes started by Administrator in E:\open\apache\spring-boot-example) 2016-06-19 19:32:34.192 INFO 10008 --- [ main] hello.Application : No active profile set, falling back to default profiles: default 2016-06-19 19:32:34.256 INFO 10008 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@12c11e94: startup date [Sun Jun 19 19:32:34 CST 2016]; root of context hierarchy 2016-06-19 19:32:35.342 INFO 10008 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http) 2016-06-19 19:32:35.353 INFO 10008 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat 2016-06-19 19:32:35.354 INFO 10008 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.33 2016-06-19 19:32:35.423 INFO 10008 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2016-06-19 19:32:35.423 INFO 10008 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1169 ms 2016-06-19 19:32:35.642 INFO 10008 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2016-06-19 19:32:35.644 INFO 10008 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2016-06-19 19:32:35.645 INFO 10008 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2016-06-19 19:32:35.645 INFO 10008 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2016-06-19 19:32:35.645 INFO 10008 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2016-06-19 19:32:35.766 INFO 10008 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@12c11e94: startup date [Sun Jun 19 19:32:34 CST 2016]; root of context hierarchy 2016-06-19 19:32:35.812 INFO 10008 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String hello.HelloController.index() 2016-06-19 19:32:35.815 INFO 10008 --- [ 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-06-19 19:32:35.815 INFO 10008 --- [ 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-06-19 19:32:35.836 INFO 10008 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2016-06-19 19:32:35.836 INFO 10008 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2016-06-19 19:32:35.875 INFO 10008 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2016-06-19 19:32:35.965 INFO 10008 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2016-06-19 19:32:36.008 INFO 10008 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 2016-06-19 19:32:36.011 INFO 10008 --- [ main] hello.Application : Started Application in 2.168 seconds (JVM running for 2.426) Let's inspect the beans provided by Spring Boot: application basicErrorController beanNameHandlerMapping beanNameViewResolver characterEncodingFilter defaultServletHandlerMapping defaultViewResolver dispatcherServlet dispatcherServletRegistration duplicateServerPropertiesDetector embeddedServletContainerCustomizerBeanPostProcessor error errorAttributes errorPageCustomizer faviconHandlerMapping faviconRequestHandler handlerExceptionResolver helloController hiddenHttpMethodFilter httpPutFormContentFilter httpRequestHandlerAdapter jacksonObjectMapper jacksonObjectMapperBuilder mappingJackson2HttpMessageConverter mbeanExporter mbeanServer messageConverters multipart.CONFIGURATION_PROPERTIES multipartConfigElement multipartResolver mvcContentNegotiationManager mvcConversionService mvcPathMatcher mvcResourceUrlProvider mvcUriComponentsContributor mvcUrlPathHelper mvcValidator mvcViewResolver objectNamingStrategy org.springframework.boot.autoconfigure.AutoConfigurationPackages org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration org.springframework.boot.autoconfigure.condition.BeanTypeRegistry org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration$DispatcherServletConfiguration org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration$TomcatWebSocketConfiguration org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.store org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor org.springframework.context.annotation.internalAutowiredAnnotationProcessor org.springframework.context.annotation.internalCommonAnnotationProcessor org.springframework.context.annotation.internalConfigurationAnnotationProcessor org.springframework.context.annotation.internalRequiredAnnotationProcessor org.springframework.context.event.internalEventListenerFactory org.springframework.context.event.internalEventListenerProcessor preserveErrorControllerTargetClassPostProcessor propertySourcesPlaceholderConfigurer requestContextFilter requestMappingHandlerAdapter requestMappingHandlerMapping resourceHandlerMapping serverProperties simpleControllerHandlerAdapter spring.http.encoding.CONFIGURATION_PROPERTIES spring.jackson.CONFIGURATION_PROPERTIES spring.mvc.CONFIGURATION_PROPERTIES spring.resources.CONFIGURATION_PROPERTIES stringHttpMessageConverter tomcatEmbeddedServletContainerFactory viewControllerHandlerMapping viewResolver websocketContainerCustomizer
有好多的默認(rèn)注入的bean. 這些bean就是spring boot強(qiáng)大功能的支持對象。
你可以通過"tomcat"關(guān)鍵字查找,能找到tomcat的蹤跡??梢愿櫾创a。
訪問http://localhost:8080/
1.6添加測試用例
在前面的pom.xml中添加
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
寫一個(gè)簡單的測試用例(這個(gè)是基于mock的方式)
package hello; import static org.hamcrest.Matchers.equalTo; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 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.SpringJUnit4Cla***unner; 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; @RunWith(SpringJUnit4Cla***unner.class) @SpringApplicationConfiguration(classes = MockServletContext.class) @WebAppConfiguration public class HelloControllerTest { 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("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("Greetings from Spring Boot!"))); } }
MockMvc來自spring-test模塊,通過一組合適構(gòu)造,發(fā)送HTTP請求。
另外一個(gè)測試用例(full-stack integration test)
package hello; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import java.net.URL; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4Cla***unner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.client.RestTemplate; @RunWith(SpringJUnit4Cla***unner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration @IntegrationTest({"server.port=0"}) public class HelloControllerIT { @Value("${local.server.port}") private int port; private URL base; private RestTemplate template; @Before public void setUp() throws Exception { this.base = new URL("http://localhost:" + port + "/"); template = new TestRestTemplate(); } @Test public void getHello() throws Exception { ResponseEntity<String> response = template.getForEntity(base.toString(), String.class); assertThat(response.getBody(), equalTo("Greetings from Spring Boot!")); } }
@IntegrationTest("${server.port=0}") 端口隨機(jī)確定
@Value("${local.server.port}")端口運(yùn)行時(shí)確定。
1.7添加生產(chǎn)環(huán)境支持
需要在pom.xml添加
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
重啟應(yīng)用,會看到增加了額外的日志
2014-06-03 13:23:28.119 ... : Mapped "{[/error],methods=[],params=[],headers=[],consumes... 2014-06-03 13:23:28.119 ... : Mapped "{[/error],methods=[],params=[],headers=[],consumes... 2014-06-03 13:23:28.136 ... : Mapped URL path [/**] onto handler of type [class org.spri... 2014-06-03 13:23:28.136 ... : Mapped URL path [/webjars/**] onto handler of type [class ... 2014-06-03 13:23:28.440 ... : Mapped "{[/info],methods=[GET],params=[],headers=[],consum... 2014-06-03 13:23:28.441 ... : Mapped "{[/autoconfig],methods=[GET],params=[],headers=[],... 2014-06-03 13:23:28.441 ... : Mapped "{[/mappings],methods=[GET],params=[],headers=[],co... 2014-06-03 13:23:28.442 ... : Mapped "{[/trace],methods=[GET],params=[],headers=[],consu... 2014-06-03 13:23:28.442 ... : Mapped "{[/env/{name:.*}],methods=[GET],params=[],headers=... 2014-06-03 13:23:28.442 ... : Mapped "{[/env],methods=[GET],params=[],headers=[],consume... 2014-06-03 13:23:28.443 ... : Mapped "{[/configprops],methods=[GET],params=[],headers=[]... 2014-06-03 13:23:28.443 ... : Mapped "{[/metrics/{name:.*}],methods=[GET],params=[],head... 2014-06-03 13:23:28.443 ... : Mapped "{[/metrics],methods=[GET],params=[],headers=[],con... 2014-06-03 13:23:28.444 ... : Mapped "{[/health],methods=[GET],params=[],headers=[],cons... 2014-06-03 13:23:28.444 ... : Mapped "{[/dump],methods=[GET],params=[],headers=[],consum... 2014-06-03 13: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(線程)
...
小計(jì):
本文章主要內(nèi)容來自http://spring.io/guides/gs/spring-boot/。不是翻譯文章,加自己的實(shí)踐說明。
真心佩服spring boot的優(yōu)雅設(shè)置。擴(kuò)展性,無侵入性都有很好的參照價(jià)值。以后有空在學(xué)習(xí)。
下一步的工作:研讀http://docs.spring.io/spring-boot/docs/1.3.5.RELEASE/reference/htmlsingle/
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。