1、为什么用Springboot?

Spring 所有具备的功能它都有,而且更容易使用;
Spring Boot 以约定大于配置的核心思想,默认帮我们进行了很多设置,多数 Spring Boot 应用只需要
很少的 Spring 配置。
Spring Boot 开发了很多的应用集成包,支持绝大多数开源软件,让我们以很低的成本去集
成其他主流开源软件

简单 Web 开发,可以手动在 pom.xml 中添加:

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

pom.xml ⽂件中默认有两个模块:
spring-boot-starter:核心模块,包括自动配置支持、日志和 YAML;
spring-boot-starter-test:测试模块,包括 JUnit、Hamcrest、Mockito。

@RestController 的意思就是 controller 里面的方法都以 json 格式输出,不用再配置什么 jackjson 的
了!
如果配置为@Controller 就代表着输出为内容。

2、热部署
热启动就需要用到我们在一开始引用的另外一个组件:Devtools。它是 Spring Boot 提供的一组开发工具包,其
中就包含我们需要的热部署功能。但是在使用这个功能之前还需要再做一些配置。
(1)在 dependency 中添加 optional 属性,并设置为 true:

<dependencies> 
   <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-Devtools</artifactId> 
      <optional>true</optional> 
   </dependency> 
</dependencies>

(2)在 plugin 中配置另外一个属性 fork,并且配置为 true:

<build> 
   <plugins> 
      <plugin> 
         <groupId>org.springframework.boot</groupId> 
         <artifactId>spring-boot-maven-plugin</artifactId> 
         <configuration> 
              <fork>true</fork> 
         </configuration> 
      </plugin> 
   </plugins> 
</build>

全部配置完成后,eclipse 就支持热部署了,大家可以试着去改动一下代码就会发现 Spring Boot 会自动重新加
载,再也不需要我们手动点击重新部署了。

@RestController 
public class HelloWorldController { 
  @RequestMapping("/hello") 
  public String index(String name) { 
     return "Hello World, " +name; 
  } 
}

单元测试

public class HelloTest { 
  @Test 
   public void hello(){ 
         System.out.println("hello world"); 
   } 
} 

单击右键“运行”按钮,会发现控制台输出:hello world。仅仅只需要了一个注解。

但是如果我们需要测试 web 层的请求呢?Spring Boot 也给出了支持。
以往我们在测试 web 请求的时候,需要自动输入相关参数在测试查看效果,或者书写 post 请求。

在 Spring Boot 中,Spring 给出了一个简单的解决方案;
使用 mockmvc 进行 web 测试,mockmvc 内置了很多工具类和方法,可以模拟 post、get 请求,并且判断返回的结果是否正确等,也可以利 print()
打印执结果。

@SpringBootTest 
public class HelloTest {
private MockMvc mockMvc;
    @Before 
    public void setUp() throws Exception { 
       mockMvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).buil d(); 
    }
    @Test 
    public void getHello() throws Exception { 
        mockMvc.perform(MockMvcRequestBuilders.post("/hello?name=neo")).andDo(prin t()); 
   } 
}

在类的上⾯添加 @SpringBootTest ,系统会自动加载 Spring Boot 容器。在日常测试中,我们就可以注入bean 来做一些局部业务的测试。
MockMvcRequestBuilders可以 post、get 请求,使用print()方法会将请求和相应的过程都打印出来。

相关文章:

  • 2021-08-06
  • 2021-05-12
  • 2021-06-07
  • 2021-07-03
  • 2021-09-15
  • 2021-05-26
  • 2021-10-04
  • 2021-12-08
猜你喜欢
  • 2021-10-21
  • 2021-11-08
  • 2022-12-23
  • 2020-12-21
  • 2022-01-07
  • 2021-08-06
  • 2019-09-17
相关资源
相似解决方案