温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Spring Boot创建一个应用

发布时间:2020-07-20 16:54:18 来源:网络 阅读:7496 作者:randy_shandong 栏目:开发技术

本文主要演示如何使用Spring Boot加速应用开发的。你可以访问Spring Initializr,快速构建属于你自己的基于Spring Boot的应用。

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

使用Spring Boot创建一个应用


1.开始构建项目

1.1)项目结构

使用Spring Boot创建一个应用

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应用

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

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

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个组合体

@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.


输出结果如下

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/

使用Spring Boot创建一个应用

1.6添加测试用例

在前面的pom.xml中添加

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

写一个简单的测试用例(这个是基于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模块,通过一组合适构造,发送HTTP请求。

另外一个测试用例(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}")  端口随机确定

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

1.7添加生产环境支持

需要在pom.xml添加

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

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

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

使用Spring Boot创建一个应用

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

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/

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI