Skip to content

webGoBetter/gs-spring-boot

Repository files navigation

tags
spring-boot
groovy
test
projects
spring-boot

本指南提供了一个示例,演示了 Spring Boot 如何帮助你加速和促进应用开发。当您阅读更多的Spring入门指南时,您会看到更多的Spring Boot用例。它的目的是让你快速尝试Spring Boot。如果你想创建自己的Spring Boot为基础的项目,访问 Spring 初始化程序,填写您的项目的详细信息,选择你的选项,你可以下载Maven构建文件,或将项目打包为一个zip文件。

你将构建什么

您将使用Spring Boot构建一个简单的Web应用程序,并向它添加一些有用的服务。

了解用Spring Boot你可以做什么

Spring Boot提供了一种快速构建应用程序的方法。在你的classpath和你已经配置了Beans中寻找,对你省略的设置做出合理的假设,然后添加进去。使用Spring Boot,您可以更多地关注业务特性,而较少关注基础设施。

举个例子:

  • 有Spring MVC吗?有几个特定的bean,你几乎总是需要,所以Spring Boot自动添加它们。Spring MVC应用程序还需要一个servlet容器,因此Spring Boot会自动配置一个嵌入式Tomcat。

  • 有Jetty吗?如果是这样,你可能不希望Tomcat,而是嵌入Jetty。Spring Boot为您处理。

  • 有Thymeleaf吗?有几个bean必须始终添加到应用程序上下文中;Spring Boot会将它们添加到您的应用程序中。

这些只是Spring Boot提供的自动配置的几个例子。同时,Spring Boot不会妨碍你的工作。例如,如果Thymeleaf在你的类路径上,Spring Boot会自动添加一个 SpringTemplateEngine 到你的应用程序的上下文中。但是如果你在你自己的设置里定义了你自己的 SpringTemplateEngine ,那么Spring Boot就不会添加它了。只需要一点点工作就可以让你控制这一切。

Note
Spring Boot 不生成代码或对文件进行编辑。相反,当启动应用程序时,Spring Boot 动态地将bean和设置连接起来,并将它们应用到应用程序上下文中。

创建一个简单的Web应用程序

现在您可以为一个简单的Web应用程序创建一个Web控制器。

src/main/java/hello/HelloController.java

link:initial/src/main/java/hello/HelloController.java[role=include]

这个类被标记为一个 @RestController ,意思是准备使用Spring MVC处理Web请求。 @RequestMapping 映射 /index() 方法。当从浏览器调用或使用命令行上的 curl 时,该方法返回纯文本。这是因为 @RestController 结合 @Controller@ResponseBody ,这两个注释会是在Web请求返回的结果是数据而不是一个视图。

创建应用程序类

在这里,您用组件创建一个应用程序类:

src/main/java/hello/Application.java

link:complete/src/main/java/hello/Application.java[role=include]

还有一个 CommandLineRunner 方法标记为 @Bean ,这会在应用启动时运行。它检索你的应用程序创建的所有bean,或者Spring Boot自动添加的。它会将它们排序后打印出来。

运行应用程序

运行应用程序,执行:

./gradlew build && java -jar build/libs/gs-spring-boot-0.1.0.jar

如果你使用 Maven, 执行:

mvn package && java -jar target/gs-spring-boot-0.1.0.jar

你应该看到一些这样的输出:

Let's inspect the beans provided by Spring Boot:
application
beanNameHandlerMapping
defaultServletHandlerMapping
dispatcherServlet
embeddedServletContainerCustomizerBeanPostProcessor
handlerExceptionResolver
helloController
httpRequestHandlerAdapter
messageSource
mvcContentNegotiationManager
mvcConversionService
mvcValidator
org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$DispatcherServletConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration
org.springframework.boot.context.embedded.properties.ServerProperties
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.web.servlet.config.annotation.DelegatingWebMvcConfiguration
propertySourcesBinder
propertySourcesPlaceholderConfigurer
requestMappingHandlerAdapter
requestMappingHandlerMapping
resourceHandlerMapping
simpleControllerHandlerAdapter
tomcatEmbeddedServletContainerFactory
viewControllerHandlerMapping

你可以清楚地看到 org.springframework.boot.autoconfigure 的bean. 还有一个 tomcatEmbeddedServletContainerFactory.

查看服务.

$ curl localhost:8080
Greetings from Spring Boot!

添加单元测试

您需要为您添加的端点添加一个测试,Spring测试已经提供了一些机制,并且很容易包含在您的项目中。

将此添加到构建文件的依赖列表中:

link:complete/build.gradle[role=include]

如果你使用Maven, 把这个添加到你的依赖列表中:

link:complete/pom.xml[role=include]

现在写一个简单的单元测试,mock 通过你的终点的servlet请求和响应:

src/test/java/hello/HelloControllerTest.java

link:complete/src/test/java/hello/HelloControllerTest.java[role=include]

MockMvc 来自 Spring Test ,允许你通过一套方便的生成器类,发送HTTP请求到 DispatcherServlet 并对结果做出的断言。注意使用的 @AutoConfigureMockMvc@SpringBootTest 一起注入 MockMvc 实例。一位使用了 @SpringBootTest 注解,我们会创建整个应用程序上下文。另一个方法是使用 @WebMvcTest 注解让Spring Boot只创建在上下文的Web层中。Spring Boot在任何情况下都自动定位应用程序的主应用程序类,但是如果您想构建不同的东西,可以重写它,或者缩小它的范围。

除了模拟HTTP请求周期,我们还可以使用 Spring Boot 来编写一个非常简单的完整堆栈集成测试。例如,我们可以像下面这样做集成测试而不是(或)上面的模拟测试:

src/test/java/hello/HelloControllerIT.java

link:complete/src/test/java/hello/HelloControllerIT.java[role=include]

嵌入式服务器根据 webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT 配置启动一个随机端口,实际的端口是可以在运行时通过 @LocalServerPort 注解注入的。

增加生产级服务

如果你要为业务构建Web站点,可能需要添加一些管理服务。 Spring Boot 提供了几个现成的 actuator module ,如健康、审计,组件,和更多。

将此添加到构建文件的依赖列表中:

link:complete/build.gradle[role=include]

如果你使用 Maven, 将此添加到列表中:

link:complete/pom.xml[role=include]

然后重启应用:

./gradlew build && java -jar build/libs/gs-spring-boot-0.1.0.jar

如果你使用 Maven, 执行:

mvn package && java -jar target/gs-spring-boot-0.1.0.jar

您将看到添加到应用程序的一组新的REST端点。这些是由Spring Boot提供的管理服务。

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...
Note
还有一个 /shutdown 端点,但默认情况下只能通过JMX看到。 作为一个HTTP端点启用 ,添加 endpoints.shutdown.enabled=true`属性到你的 `application.properties 文件中。

很容易检查应用程序的健康状况。

$ curl localhost:8080/health
{"status":"UP","diskSpace":{"status":"UP","total":397635555328,"free":328389529600,"threshold":10485760}}}

您可以尝试通过curl调用关机。

$ curl -X POST localhost:8080/shutdown
{"timestamp":1401820343710,"error":"Method Not Allowed","status":405,"message":"Request method 'POST' not supported"}

因为我们没有启用它,所以请求被端点不存在的缘故阻塞。

关于这些REST端点更多的细节,和你如何用 application.properties 文件调整自己的设置,你可以阅读详细的http://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/htmlsingle/#production-ready-endpoints[docs about the endpoints] 。

查看Spring Boot starter程序

你已经看到了一下 Spring Boot’s "starters". 你可以在这里看到他们的全部 here in source code.

jar支持和Groovy支持

最后一个例子说明了Spring Boot如何轻松地添加那些你自己都没有意识到你会需要的组件。并展示了如何开启便捷的管理服务。

但 Spring Boot 甚至做得更多。它不仅支持传统的WAR文件部署,而且还可以很容易地将可执行的 JARs 放在一起,这多亏了Spring的启动加载模块。各种指南展示了这种对 spring-boot-gradle-pluginspring-boot-maven-plugin 的双重支持。

最重要的是,Spring Boot还具有Groovy支持,允许您只使用一个文件构建Spring MVC Web应用程序。

创建一个名为 app.groovy 的新文件,并将下面的代码放入其中:

@RestController
class ThisWillActuallyRun {

    @RequestMapping("/")
    String home() {
        return "Hello World!"
    }

}
Note
文件在哪里并不重要。你甚至可以在 single tweet 内部安装一个小应用程序!

如下所示运行:

$ spring run app.groovy
Note
假设您关闭了以前的应用程序,以避免端口冲突。

从不同的终端窗口:

$ curl localhost:8080
Hello World!

Spring Boot是通过动态地为你的代码添加关键注释,然后使用使用 Groovy Grape 拉取所需的库以使应用运行。

总结

祝贺你!使用Spring Boot构建了一个简单的Web应用程序,并学习了如何提高开发速度。您还打开了一些便利的生产服务。 这只是一个关于Spring Boot可以做什么小示例。如果你想了解得更深入点,访问 Spring Boot在线文档

About

使用Spring Boot构建应用程序 :: 学习如何以最少的配置构建应用程序。

Resources

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors