用SpringBoot构建应用程序

 

用SpringBoot构建应用程序

本指南提供了如何使用SpringBoot帮助您加速和促进应用程序开发。当您阅读更多Spring入门指南时,您将看到SpringBoot的更多用例。它的目的是给你一个快速的春天启动的味道。如果您想创建自己的基于SpringBoot的项目,请访问https://start.spring.io/,填写项目详细信息,选择选项,您可以下载Maven构建文件,也可以下载打包成zip文件的项目。

你要建什么

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

你需要什么

如何完成本指南

像大多数春天一样入门指南,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,你最终都会得到工作代码。

白手兴家,继续前进用Gradle建造.

跳过基础,做以下工作:

当你完成中的代码检查结果。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-pluginspring-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的在线文档如果你想挖得更深。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值