zoukankan      html  css  js  c++  java
  • 使用Spring Boot构建应用程序(Building an Application with Spring Boot)

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

    你会建立什么

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

    你需要什么

     大约15分钟

     Intellij IDEA

     Maven

    如何完成本指南

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

    打开Idea-> new Project ->Spring Initializr ->填写group、artifact ->钩上web(开启web功能)->点下一步就行了。

    了解您可以用Spring Boot做什么

    Spring Boot提供了构建应用程序的快速方法。它会查看你的类路径和已配置的beans,并对你所缺少的内容进行合理的假设,并添加它。通过Spring Boot,你可以更多地关注业务功能,减少配置。

    例如:构建Spring MVC。有几个特定的beans几乎总是需要的,Spring Boot会自动添加它们。Spring MVC应用程序还需要一个servlet容器,所以Spring Boot自动配置嵌入式Tomcat。

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

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

    package com.example.demo.web;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class HelloController {
        @RequestMapping("/")
        public String index() {
            return "Greetings from Spring Boot!";
        }
    }

    该类被标记为@RestController,意味着它已经可以被Spring MVC用来处理web请求。@RequestMapping映射 index()方法。当从浏览器调用时,改方法将返回纯文本。这是因为@RestController结合@Controller@ResponseBody两个注释,导致Web请求返回数据而不是视图。

    创建一个应用程序类

    使用components创建一个Application类

    package com.example.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class FirstApplication {
        public static void main(String[] args) {
            SpringApplication.run(FirstApplication.class, args);
        }
    }

    @SpringBootApplication是一个方便的注释,它包括@Configuration、@EnableAutoConfiguration 、@EnableWebMvc、@ComponentScan

    • @Configuration将该类标记为应用程序上下文的bean定义的来源。
    • @EnableAutoConfiguration告诉Spring Boot根据类路径设置、其他bean和各种属性设置添加bean。
    • 通常情况下,你需要为一个Spring MVC应用添加@EnableWebMvc,但是Spring Boot在classpath(类路径)中看到spring-webmvc时自动添加它。这(添加@EnableWebMvc)将该应用程序标记为Web应用程序,并激活如设置DispatcherServlet之类的关键行为。
    • @ComponentScan告诉Spring在类自己属于的包(com.example.demo)中查找其他组件、配置和服务,以便找到控制器。

    main()方法使用Spring Boot的SpringApplication.run()方法来启动应用程序。你有没有注意到没有一行XML?没有web.xml文件。这个Web应用程序是100%纯Java,你不必配置任何管道或基础设施。

    添加单元测试

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

    将其添加到你的Maven依赖关系列表中:

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

    现在编写一个简单的单元测试,模拟servlet请求和响应通过你的端点。

    package com.example.demo;
    
    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 getHollo() throws Exception {
            mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
                    .andExpect(status().isOk())
                    .andExpect(content().string(equalTo("Greetings from Spring Boot!")));
        }
    }

    Spring Test组件里的MockMvc类,允许我们通过一组方便的构建器类,将HTTP请求发送到DispatcherServlet,并对结果进行断言。请注意,使用@AutoConfigureMockMvc@SpringBootTest来注入一个MockMvc实例。使用了@SpringBootTest,我们要求的完整的应用程序上下文就被创建了。另一种方法是,使用@WebMvcTest只创建web层的上下文。Spring Boot自动尝试定位应用程序的主应用类,但是如果你想构建不同的,你可以重写它,或者缩小它。

    除了模拟HTTP请求,我们还可以使用Spring Boot编写一个非常简单的全栈集成测试。

    package com.example.demo;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.context.embedded.LocalServerPort;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.boot.test.web.client.TestRestTemplate;
    import org.springframework.http.ResponseEntity;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import java.net.URL;
    
    import static org.hamcrest.Matchers.equalTo;
    import static org.junit.Assert.assertThat;
    
    @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,在运行时找到当前的端口。

    添加生产级服务

    如果你为你的业务构建一个web站点,你可能需要添加一些管理服务。Spring Boot提供了几个开箱即用的执行器模块,如健康、审计、beans等

    将其添加到你的依赖项列表:

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

    你将看到一组新的RESTful终端添加到应用程序中。这些是由Spring Boot提供的管理服务。

    在application.properties,添加management.security.enabled=false。你就可以访问http://localhost:8080/health。

    它们包括:错误、环境、健康、beans、信息、指标,跟踪、配置支持和转储。

    参考资料:Building an Application with Spring Boot

    SpringBoot非官方教程 | 第一篇:构建第一个SpringBoot工程 - 方志朋的专栏 - CSDN博客

    源码:https://gitee.com/SevenDayBabyface/demo

  • 相关阅读:
    不过的小东东
    基础练习 特殊回文数
    基础练习 特殊回文数
    基础练习 特殊回文数
    web.input()与web.data()函数比较
    web.input()与web.data()函数比较
    web.input()与web.data()函数比较
    MFC 服务管理
    Fedora Documentation
    Centos7 安装vnc
  • 原文地址:https://www.cnblogs.com/xsj891107/p/7919457.html
Copyright © 2011-2022 走看看