使用Spring Boot创建一个应用

简介:

如图,一键即可生成项目。

wKioL1dmexeBL2F6AACsZ_KThjg546.png


1.开始构建项目

1.1)项目结构

wKioL1dmfCHxea0mAAAs-biupz4248.png

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,作为单个可运行的“ü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应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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表示类准备使用SpringMVC处理web请求,绑定了@Controller和@ResponseBody

1
2
3
4
5
6
7
8
9
10
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创建一个应用Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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个组合体

1
2
3
4
5
6
7
8
9
10
@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中发现 spring-webmvc 
,会自动添加@EnableWebMvc;

SpringApplication.run() 启动应用入口,没有web.xml,没有application.xml.100%的java.


输出结果如下

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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

有好多的默认注入的bean. 这些bean就是spring boot强大功能的支持对象。

你可以通过"tomcat"关键字查找,能找到tomcat的踪迹。可以跟踪源码。


访问http://localhost:8080/

wKiom1dmhJqDq2EYAAAWdxUgnC4032.png

1.6添加测试用例

在前面的pom.xml中添加

1
2
3
4
5
         < dependency >
             < groupId >org.springframework.boot</ groupId >
             < artifactId >spring-boot-starter-test</ artifactId >
             < scope >test</ scope >
         </ dependency >

写一个简单的测试用例(这个是基于mock的方式)

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
32
33
34
35
36
37
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.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;
 
@RunWith (SpringJUnit4ClassRunner. 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模块,通过一组合适构造,发送HTTP请求。

另外一个测试用例(full-stack integration test)

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
32
33
34
35
36
37
38
39
40
41
42
43
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.SpringJUnit4ClassRunner;
import  org.springframework.test.context.web.WebAppConfiguration;
import  org.springframework.web.client.RestTemplate;
 
@RunWith (SpringJUnit4ClassRunner. 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}")  端口随机确定

@Value("${local.server.port}")端口运行时确定。

1.7添加生产环境支持

需要在pom.xml添加

1
2
3
4
         < dependency >
             < groupId >org.springframework.boot</ groupId >
             < artifactId >spring-boot-starter-actuator</ artifactId >
         </ dependency >

重启应用,会看到增加了额外的日志

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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

wKioL1dmiIDBV9EKAAAtSz1tJ3Y267.png

还有一些线上排查诊断问题其他功能:

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/



本文转自 randy_shandong 51CTO博客,原文链接:http://blog.51cto.com/dba10g/1790856,如需转载请自行联系原作者

相关文章
|
22天前
|
Java 应用服务中间件 Maven
SpringBoot 项目瘦身指南
SpringBoot 项目瘦身指南
38 0
|
1月前
|
监控 Java 数据处理
【Spring云原生】Spring Batch:海量数据高并发任务处理!数据处理纵享新丝滑!事务管理机制+并行处理+实例应用讲解
【Spring云原生】Spring Batch:海量数据高并发任务处理!数据处理纵享新丝滑!事务管理机制+并行处理+实例应用讲解
|
2月前
|
XML Java 数据格式
Spring 应用上下文探秘:生命周期解析与最佳实践
Spring 应用上下文探秘:生命周期解析与最佳实践
73 0
|
2月前
|
存储 Java Maven
QR码应用实战:Spring Boot与ZXing完美结合
QR码应用实战:Spring Boot与ZXing完美结合
28 0
|
2月前
|
消息中间件 存储 监控
搭建消息时光机:深入探究RabbitMQ_recent_history_exchange在Spring Boot中的应用【RabbitMQ实战 二】
搭建消息时光机:深入探究RabbitMQ_recent_history_exchange在Spring Boot中的应用【RabbitMQ实战 二】
32 1
|
21天前
|
安全 Java 数据安全/隐私保护
【深入浅出Spring原理及实战】「EL表达式开发系列」深入解析SpringEL表达式理论详解与实际应用
【深入浅出Spring原理及实战】「EL表达式开发系列」深入解析SpringEL表达式理论详解与实际应用
44 1
|
2月前
|
消息中间件 NoSQL Java
Redis Streams在Spring Boot中的应用:构建可靠的消息队列解决方案【redis实战 二】
Redis Streams在Spring Boot中的应用:构建可靠的消息队列解决方案【redis实战 二】
187 1
|
2月前
|
缓存 Java 数据库
优化您的Spring应用程序:缓存注解的精要指南
优化您的Spring应用程序:缓存注解的精要指南
42 0
|
1天前
|
安全 Java 应用服务中间件
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
4 0
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
|
3天前
|
XML Java C++
【Spring系列】Sping VS Sping Boot区别与联系
【4月更文挑战第2天】Spring系列第一课:Spring Boot 能力介绍及简单实践
28 0
【Spring系列】Sping VS Sping Boot区别与联系