环境
MacBook Pro
java:1.8
gradle:5.5.1
IntelliJ IDEA : 2019.2
前言
翻译官网
用springboot来构建一个应用程序
用gradle来构建
首先,我们要设置一个基本脚本。在使用Spring
构建应用程序时,可以使用任何喜欢的构建系统,这里是两个常用构建工具的地址:gradle和maven;
如果这两个构建工具都不熟悉的话,可以参考:
Building Java Projects with Gradle
Building Java Projects with Maven.
创建目录结构
在我们的项目目录中,创建以下子目录结构;
例如:mkdir -p src/main/java/hellop
(Linux
)
|___ src
|___main
|___java
|___hello
创建gradle构建文件
github上的地址:initial Gradle build file.
文件名:build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.2.1.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")
}
Spring Boot gradle plugin 提供了许多方便的特性:
- 它会收集类路径上的所有
jar
,并构建一个可运行的单个jar
包,这样执行起来或者传输起来很方便 - 它会搜索
public static void main()
方法并标记为可运行类。 - 它提供了一个内置的
依赖解析器
,用于设置版本号以匹配springboot dependencies
。你可以覆盖所需的任何版本,但是springboot会提供一个默认版本。
了解使用springboot可以做什么
springboot提供了一种构建应用程序的快速方法。它会查看你的类路径和你配置的bean,对丢失的内容作出合理的假设,然后添加。
借助springboot你可以将更多的精力放在业务功能上,而不必在基础架构上。
例如:
- 需要
SpringMVC
吗?我们几乎总是需要几个特定的bean
,现在Spring Boot
会自动添加它们。SpringMVC
应用程序还需要一个servlet
容器,因此Spring Boot
会自动配置嵌入式Tomcat
。 - 需要
Jetty
吗?如果是的话,你可能不希望使用Tomcat
,而希望使用Jetty
。Spring Boot
会帮你处理该问题。 - 需要
Thymeleaf
吗?有少部分beans必须添加到你的应用上下文中;Spring Boot
会帮你添加。
上面只是Spring Boot
提供的自动配置的一些示例。
同时,Spring Boot
不会妨碍你。
例如:
如果Thymeleaf
在你的路径上,则Spring Boot
会自动将SpringTemplateEngine
添加到您的应用程序上下文中。
但是,如果你设置使用自定义的SpringTemplateEngine
,则Spring Boot
不会添加一个,这样你可以毫不费力的进行控制。
Spring Boot 不会生成代码或者对文件进行编辑。
相反,当你启动应用程序时,Spring Boot会动态地连接bean和设置并将它们应用于你的应用程序上下文。
创建一个简单的Web应用程序
现在,你可以为简单的Web应用程序创建一个Web
Controller
。
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!";
}
}
上面HelloController.java
类被@RestController
标记,这意味着Spring MVC
可以使用该类来处理Web
请求。
@RequestMappping将/
映射到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
的源头。
通俗点将,就是以前bean都是配置在xml
文件中的,现在把一个类标记为@Configuration
后,那么bean
就可以配置在该类里面,替代了xml
文件的作用。 -
@EnableAutoConfiguration
: 告诉Spring Boot
根据类路径的设置、其他bean
和各种属性的设置来添加bean
例如:
如果Spring-webmvc
在类路径上,则此注解将应用程序标记为Web应用程序并激活关键行为,例如设置DispatcherServlet
。 -
@ComponentScan
: 告诉Spring 在hello包下,寻找其他components
、configurations
和services
,让它找到controllers
。
main()
方法使用的是Spring Boot的SpringApplication.run()
方法来启动应用程序。你是否注意到了这里没有一行XML
,也没有web.xml
文件。
这个web application是一个100%的纯java程序,因此你无需处理任何管道和基本结构。
还有一个标记为@Bean
的CommandLineRuner
方法,该方法在启动时运行。
这个方法会检索由你的应用程序创建或由于Spring Boot而自动添加的所有的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
你将会看到如下信息:
你可以清晰的看到org.springframework.boot.autoconfigure
下的beans.
也能看到tomcatServletWebServerFactory
。
检查服务:
执行命令:
curl localhost:8080
添加单元测试
添加测试,Spring Test已经为此提供了一些机制,并且很容易包含在你的项目中。
将下面代码添加到构建文件的dependencies
中:
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来自Spring Test,它允许你通过一组方便的构造器类将HTTP请求发送到DispatcherServlet
中,并对结果进行断言。
请注意:将@AutoConfigureMockMvc和@SpringBootTest一起使用以注入MockMvc
实例。使用@SpringBootTest之后,我们要求创建整个应用程序上下文。一种替代方法是使用@WebMvcTest要求Spring Boot仅创建Web层的上下文。
在任何一种情况下,Spring Boot都会自动尝试查找应用程序的主应用程序类,
但是如果你想构建其他内容,则可以覆盖或者缩小它的范围。
除了模拟HTTP请求周期外,我们还可以使用Spring Boot编写一个非常简单的full-stack
集成测试。例如:除了上面的模拟测试,我们可以这样做:
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
在随机端口上启动嵌入式服务器,并在运行时使用@LocalServerPost
发现实际端口。
添加生产级services
如果你要构建企业级网站,则可能需要添加一些管理服务。
Spring Boot提供了一些开箱即用的执行器模块,例如:运行状况,审计,bean等。
在构建文件中dependencies
中添加:
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
端点添加到了应用程序。
这些是Spring Boot提供的管理服务。
它们包括errors
,actuator/health, actuator/info, actuator.
还有一个/actuator/shutdown 端点,但是默认情况下只能通过JMX看到。
想启用HTTP端点,在application.properties文件中添加management.endpoints.shutdown.enabled=true
检查应用程序健康状况变得很容易:
$ 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"}
因为并没有启用它,因此该请求由于不存在而被阻止。
关于每个REST
点以及如何使用application.properties文件(在src/main/resources中)调整其设置的更多详情信息,可以阅读有关端点的详细文档。
查看Spring Boot启动器
你可以查看一些Spring Boot的启动器。
查看这些启动器的源码
jar支持和groovy支持
最后一个例子展示了SpringBoot如何使连接您可能不知道需要的bean变得容易。展示了如何开启便捷的管理服务。
但是Spring Boot还有更多功能。
它不仅支持传统的WAR文件部署,而且借助Spring Boot的加载程序模块,还可以轻松地将可执行的JAR放在一起。
各种指南通过spring-boot-gradle-plugin
和spring-boot-maven-plugin
演示了这种双重支持。
最重要的是,Spring Boot还具有Groovy支持,使您仅用一个文件就可以构建Spring MVC Web应用程序。
创建一个名为app.groovy的新文件,并将以下代码放入其中:
@RestController
class ThisWillActuallyRun {
@RequestMapping("/")
String home() {
return "Hello World!"
}
}
文件在哪里都没有关系。您甚至可以在一个推文中包含一个很小的应用程序!
执行如下命令:
$ spring run app.groovy
建议您关闭了先前的应用程序,以避免端口冲突。
在另一个终端窗口中:
$ curl localhost:8080
Hello World!
Spring Boot通过在代码中动态添加关键注释并使用Groovy Grape来拉取使应用程序运行所需的库来实现此目的。