用SpringBoot构建应用程序
本指南提供了如何使用SpringBoot帮助您加速和促进应用程序开发。当您阅读更多Spring入门指南时,您将看到SpringBoot的更多用例。它的目的是给你一个快速的春天启动的味道。如果您想创建自己的基于SpringBoot的项目,请访问https://start.spring.io/,填写项目详细信息,选择选项,您可以下载Maven构建文件,也可以下载打包成zip文件的项目。
你要建什么
您将使用SpringBoot构建一个简单的Web应用程序,并向其添加一些有用的服务。
你需要什么
-
大约15分钟
-
最喜欢的文本编辑器或IDE
-
JDK 1.8或以后
-
您还可以直接将代码导入IDE中:
如何完成本指南
像大多数春天一样入门指南,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,你最终都会得到工作代码。
到白手兴家,继续前进用Gradle建造.
到跳过基础,做以下工作:
-
下载并解压缩本指南的源存储库,或使用git:
git clone https://github.com/spring-guides/gs-spring-boot.git
-
CD成
gs-spring-boot/initial
-
跳到[初始].
当你完成中的代码检查结果。gs-spring-boot/complete
.
用Gradle建造
首先,您设置了一个基本的构建脚本。在使用Spring构建应用程序时,您可以使用任何您喜欢的构建系统,但是您需要使用的代码梯度和马文包括在这里。如果你对两者都不熟悉,请参考用Gradle构建Java项目或使用Maven构建Java项目.
创建目录结构
在您选择的项目目录中,创建以下子目录结构;例如,使用mkdir -p src/main/java/hello
关于*nix系统:
└── src
└── main
└── java
└── hello
创建一个Gradle构建文件
下面是初始分级生成文件.
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.5.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
bootJar {
baseName = 'gs-spring-boot'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("junit:junit")
}
这,这个,那,那个弹簧启动级插件提供了许多方便的功能:
-
它收集类路径上的所有JAR,并构建一个可运行的“über-jar”,这使得执行和传输服务更加方便。
-
它搜索
public static void main()
方法标记为可运行的类。 -
它提供了一个内置的依赖项解析器,它将版本号设置为匹配。弹簧启动依赖关系。您可以覆盖任何版本,但它将默认为Boot所选的一组版本。
用Maven构建
用IDE构建
学习使用SpringBoot可以做什么
SpringBoot提供了一种快速构建应用程序的方法。它查看类路径和配置的bean,对所缺少的内容做出合理的假设,并添加它。使用SpringBoot,您可以更多地关注业务特性,而更少关注基础设施。
例如:
-
有SpringMVC吗?您几乎总是需要几个特定的bean,SpringBoot会自动添加它们。SpringMVC应用程序还需要一个servlet容器,因此SpringBoot会自动配置嵌入式Tomcat。
-
有Jetty吗?如果是这样的话,您可能不需要Tomcat,而是需要嵌入式Jetty。春靴帮你处理。
-
找到Thymeleaf了吗?有些bean必须始终添加到应用程序上下文中;SpringBoot为您添加了它们。
这些只是SpringBoot提供的自动配置的几个例子。同时,SpringBoot不会妨碍您。例如,如果Thymeleaf在您的路径上,Spring Boot将添加一个SpringTemplateEngine
自动发送到应用程序上下文。但是如果你定义你自己的SpringTemplateEngine
使用您自己的设置,那么SpringBoot将不会添加一个。这只会让你控制局面,而你的努力却微乎其微。
SpringBoot不生成代码,也不对文件进行编辑。相反,在启动应用程序时,SpringBoot动态地连接bean和设置,并将它们应用到应用程序上下文中。 |
创建一个简单的web应用程序
现在,您可以为一个简单的Web应用程序创建一个Web控制器。
src/main/java/hello/HelloController.java
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请求做好了准备。@RequestMapping
地图/
到index()
方法。当从浏览器调用或在命令行上使用curl时,该方法将返回纯文本。那是因为@RestController
联合@Controller
和@ResponseBody
,这两个注释导致Web请求返回数据而不是视图。
创建应用程序类
在这里,您创建了一个Application
使用以下组件初始化:
src/main/java/hello/Application.java
package hello;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return 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
是一个方便的注释,它添加了以下所有内容:
-
@Configuration
将类标记为应用程序上下文的bean定义的源。 -
@EnableAutoConfiguration
告诉SpringBoot根据类路径设置、其他bean和各种属性设置开始添加bean。 -
通常你会添加
@EnableWebMvc
对于SpringMVC应用程序,但是SpringBoot在看到Springwebmvc在类路径上。这会将应用程序标记为web应用程序,并激活关键行为,例如设置DispatcherServlet
. -
@ComponentScan
告诉Spring在hello
包,让它找到控制器。
这,这个,那,那个main()
方法使用SpringBoot的SpringApplication.run()
方法来启动应用程序。您注意到没有一行XML吗?否web.xml也要归档。这个Web应用程序是100%纯Java的,您不必处理配置任何管道或基础设施的问题。
还有一个CommandLineRunner
方法标记为@Bean
这件事一开始就开始了。它检索所有由应用程序创建或由于SpringBoot自动添加的bean。把它们分类打印出来。
运行应用程序
要运行应用程序,请执行:
./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豆子还有一个tomcatEmbeddedServletContainerFactory
.
看一下服务。
$ curl localhost:8080
Greetings from Spring Boot!
添加单元测试
您将希望为您添加的端点添加一个测试,SpringTest已经为此提供了一些机制,并且很容易将其包含到您的项目中。
将此添加到构建文件的依赖项列表中:
testCompile("org.springframework.boot:spring-boot-starter-test")
如果使用的是Maven,请将其添加到依赖项列表中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
现在编写一个简单的单元测试,通过端点模拟servlet请求和响应:
src/test/java/hello/HelloControllerTest.java
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.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mvc;
@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
来自SpringTest,并允许您通过一组方便的构建器类将HTTP请求发送到DispatcherServlet
并对结果做出断言。注意使用@AutoConfigureMockMvc
连同@SpringBootTest
注入MockMvc
举个例子。用过@SpringBootTest
我们要求创建整个应用程序上下文。另一种选择是要求SpringBoot只使用@WebMvcTest
。Spring Boot在任何情况下都会自动尝试定位应用程序的主应用程序类,但是如果您想要构建不同的东西,可以重写它,或者缩小它的范围。
除了模拟HTTP请求周期之外,我们还可以使用SpringBoot编写一个非常简单的全堆栈集成测试。例如,我们可以这样做,而不是(或者)上面的模拟测试:
src/test/java/hello/HelloControllerIT.java
package hello;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.net.URL;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerIT {
@LocalServerPort
private int port;
private URL base;
@Autowired
private TestRestTemplate template;
@Before
public void setUp() throws Exception {
this.base = new URL("http://localhost:" + port + "/");
}
@Test
public void getHello() throws Exception {
ResponseEntity<String> response = template.getForEntity(base.toString(),
String.class);
assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
}
}
嵌入式服务器是在一个随机端口上启动的。webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
并在运行时发现实际端口。@LocalServerPort
.
增加生产级服务
如果您正在为您的业务构建一个网站,您可能需要添加一些管理服务。Spring Boot提供了几个开箱即用的执行器模块,如健康、审计、豆类等。
将此添加到构建文件的依赖项列表中:
compile("org.springframework.boot:spring-boot-starter-actuator")
如果使用的是Maven,请将其添加到依赖项列表中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
然后重新启动应用程序:
./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
您将看到一组新的RESTful端点添加到应用程序中。这些是SpringBoot提供的管理服务。
2018-03-17 15:42:20.088 ... : Mapped "{[/error],produces=[text/html]}" onto public org.s...
2018-03-17 15:42:20.089 ... : Mapped "{[/error]}" onto public org.springframework.http.R...
2018-03-17 15:42:20.121 ... : Mapped URL path [/webjars/**] onto handler of type [class ...
2018-03-17 15:42:20.121 ... : Mapped URL path [/**] onto handler of type [class org.spri...
2018-03-17 15:42:20.157 ... : Mapped URL path [/**/favicon.ico] onto handler of type [cl...
2018-03-17 15:42:20.488 ... : Mapped "{[/actuator/health],methods=[GET],produces=[application/vnd...
2018-03-17 15:42:20.490 ... : Mapped "{[/actuator/info],methods=[GET],produces=[application/vnd.s...
2018-03-17 15:42:20.491 ... : Mapped "{[/actuator],methods=[GET],produces=[application/vnd.spring...
还有一个/actuator/shutdown 端点,但它仅在默认情况下通过JMX可见。到将其启用为HTTP端点,添加management.endpoints.shutdown.enabled=true 敬你的application.properties 档案。 |
很容易检查应用程序的健康状况。
$ curl localhost:8080/actuator/health
{"status":"UP"}
您可以尝试通过curl调用关机。
$ curl -X POST localhost:8080/actuator/shutdown
{"timestamp":1401820343710,"error":"Method Not Allowed","status":405,"message":"Request method 'POST' not supported"}
因为我们没有启用它,所以请求被不存在的优点所阻止。
有关每个休息点的更多详细信息,以及如何使用application.properties
文件,您可以详细阅读。关于端点的文档.
查看Spring Boot的启动器
JAR支持和Groovy支持
最后一个示例展示了SpringBoot如何使连接bean变得简单,您可能不知道自己需要什么。并展示了如何打开方便的管理服务。
但是Spring Boot做的更多。它不仅支持传统的WAR文件部署,而且由于SpringBoot的加载程序模块,可以轻松地将可执行的JAR放在一起。各种指南通过spring-boot-gradle-plugin
和spring-boot-maven-plugin
.
除此之外,SpringBoot还提供了Groovy支持,允许您只使用一个文件就可以构建SpringMVC Web应用程序。
创建一个名为app.groovy并将以下代码放入其中:
@RestController
class ThisWillActuallyRun {
@RequestMapping("/")
String home() {
return "Hello World!"
}
}
文件在哪里并不重要。您甚至可以在单推! |
接下来,安装SpringBoot的CLI.
按以下方式运行:
$ spring run app.groovy
这假设您关闭了上一个应用程序,以避免端口冲突。 |
从不同的终端窗口:
$ curl localhost:8080
Hello World!
SpringBoot通过将键注释动态添加到代码中,并使用花纹葡萄要减少运行应用程序所需的库,请执行以下操作。
摘要
祝贺你!您使用SpringBoot构建了一个简单的Web应用程序,并了解了它如何加快您的开发速度。您还打开了一些方便的生产服务。这只是SpringBoot能做什么的一个小样本。结帐Spring Boot的在线文档如果你想挖得更深。