写在前面

现在已经是八月份了,我已经荒废了半年居多,不得不说谈恋爱确实是个麻烦的事,谈好了皆大欢喜,分手了就是萎靡不振,需要很长一段时间才能缓过来。

人还是要有梦想的,至于实现只不过是一个契机,但凡不懒,你都可能是下一个被命运眷顾的幸运儿(仅限技术,追妹纸另当别论)。

一直以来就有个心愿,想使用前后端分离技术,写一个Web系统,主要技术栈Spring Boot+ Vue3 ,想一想就很兴奋那种,很久没有这种感觉了。

话不多说,开始更文了。

创建Spring Boot项目

  • 单击 File -> New -> Project… 命令,弹出新建项目框。

  • 选择 Spring Initializr 选项,单击 Next 按钮,Idea 很强大已经帮我们做了集成。

  • 选择 Web ,这里我选择的版本是2.4.0,如果无法选中,到时候在pom文件中自行修改即可,单击Next按钮,最后确定信息无误单击 Finish 按钮。
    寻找写代码感觉(一)之使用 Spring Boot 快速搭建项目-LMLPHP

  • 删除无用的文件.mvn、 mvnw、 mvnw.cmd
    寻找写代码感觉(一)之使用 Spring Boot 快速搭建项目-LMLPHP

项目结构

  • src/main/java:程序开发以及主程序入口
  • src/main/resources:配置文件
  • src/test/java:测试程序

简单接口编写

按照国际惯例,先整一个Hello World吧。
首先创建一个名为HelloController的类,示例代码如下:

package com.rongrong.wiki.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
*
* @description
* @version 1.0
* @author longrong.lang
*
*/
@RestController
public class HelloController {
    @RequestMapping(method= RequestMethod.GET,value = "/hello")
    public String sayHello(){
        return "hello,Spring Boot!";
    }
}

启动主程序

打开浏览器访问 http://localhost:8080/hello,就可以看到以下内容:

hello,Spring Boot!

单元测试

我们使用Spring Boot中自带的MockMvc进行测试,不了解的同学可以自己百度查询学习,如果对PowerMock或者其他单元测试框架Mock比较书的同学上手会很快。

在测试程序中,创建一个名为HelloControllerTest的测试类,示例代码如下:

package com.rongrong.wiki.test;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
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.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

/**
 * @author longrong.lang
 * @version 1.0
 * @description
 */
@AutoConfigureMockMvc
@SpringBootTest
public class HelloControllerTest {
    @Autowired
    MockMvc mockMvc;

    @Test
    @DisplayName("测试返回字符串")
    public void testHello() throws Exception {
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_FORM_URLENCODED)).andReturn();
        String content = mvcResult.getResponse().getContentAsString();
        assertThat(content,equalTo("hello,Spring Boot!"));
    }

}

说明:

  • @Autowired这个注解应该很熟悉吧,个人感觉这里采用的是Spring Mvc的思路,比如自动导入Bean
  • 关于Mock部分参考单元测试框架Mock去学习即可

运行结果

寻找写代码感觉(一)之使用 Spring Boot 快速搭建项目-LMLPHP

最后

到此,使用 Spring Boot 快速搭建项目完成,如果觉得对您有帮助,请关注,点赞,并转发。

聪明的人都去瞧瞧努力了,你还在犹豫什么呢?行动起来,来一起入坑!

08-18 04:35