SpringBoot笔记

Idea环境

创建项目:

 

 

 Webflux响应式编程

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>true</scope> 
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    <exclusions>
</dependency>

<d>热部署ctrl+shift+alt+/设置允许程序运行时编译
    <g>org.springframework.boot</g>
    <a>spring-boot-devtools</a>
    <o>true</o>
</d>

<d>Excel处理类返回响应下载
    <g>org.apache.poi</g>
    <a>poi-ooxml</a>
    <v>3.9</v>
</d>    

 

//lombok
@Data
@Slf4j
@Builder
@AllArgsConstructor
@NoArgsConstructor
Person person = Person.builder().name("").age("").build();

快捷键:

ctrl+shift+alt+/

 

 谷歌插件,Live Reload前端写脚本无需刷新页面

 

 

第六讲:

五个插件

 

1. Setting --> Plugins 搜索Codota代码自动补全引包

2.Auto filling Java call arguments (在构造函数中按alt+enter,选择auto filling)

3.GsonFormat根据json字符串生成 对象快捷键Alt+s或是按两下shift搜索alt+s

4.Rainbow Brackets 括号颜色标记

5.Dependency Analyzer

 第六讲 Restful

名词复数命名

 

 

 

 

 

 

Spring常用注解
@Resource
@Autowired
@RestController
@GetMapping("/articles/{id}")
@PostMapping
@PutMapping
@DeleteMapping @RequestMapping(value
="/articles/{id}",method=RequestMethod.GET) @PathVariable("id") String id
@RequestBody
@RequestParam String author,
//PostMan请求时,使用Body -> form-data模拟表单提交和Params-->Key Value
public void saveArticle(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam Date createTime)
//PostMan请求头传参 Headers -> Key Value
public void saveArticle(@RequestHeader String aaa)
@PostMapping("/hello/{name}")//如果反回字符串,默认去resources/templates下面查找jsp,freemarker等页面。
public String save(@Variable String name){}

JSON注解及实体类应用中的作用:
//类名标注:属性顺序调整
@JsonPropertyOrder(value={"pname1","pname2"})
//忽略某个属性,不需要返回的属性
@JsonIgnore
//修改属性名
@JsonProperty("auther")
private String aother;
//属性为空时,不返回属性
@JsonInclude(JsonInclude.Include.NON_NULL)
private List<Reader> reader;
//实体类中
@JsonFormat(pattern="yyyy/MM/dd HH:mm:ss",timezone="GMT+8")
private Date createTime;

//java对象和json字符串主换类(手动转换JSON对象和字符串)
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(article);
Article article1 = mapper.readValue("JSON", Article.class);


如下前后端传参:

@Resource
private ObjectMapper mapper;

@ApiParam(name = "接收json参数", defaultValue = "{}") @RequestBody String json

Map map = null;
try {
map = mapper.readValue(json, Map.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
System.out.println(map);

 HttpMessageConverter (序列化和反序列化JSON,XML,EXCEL等)

application.yml配置

server:
    port: 8888

spring:
    jackson:
        date-format: yyyy-MM-dd HH:mm:ss
        time-zone: GMT+8

 

单元测试:

Junit5

Mockito

spring-boot-starter-rest(包含Junit和Mockito)

test package通过Maven打包执行测试用例。

测试环境启用Servlet环境@Slf4j

//当测试代码中需要依赖注入时使用以下3个注解。
@AutoConfigureMockMvc
@SpringBootTest//springboot上下文包括各种注解的使用 ----------轻量级Mock测试时,只使用@WebMvcTest(ArticleController.class只针对这一个,不加时对所有Bean加载)
//@RunWith(SpringRunner.class) //Junit4开发者使用这个注解
@ExtendWith(SpringExtension.
class)//spring运行时环境依赖注入servlet环境
@Slf4j
@AutoConfigureMockMvc
@SpringBootTest
@ExtendWith(SpringExtension.class)
public class Test 
{
    //mock对象
    @Resource
    private static MockMvc mockMvc;

    /*
    @BeforeAll
    static void setUP() {
        mockMvc = MockMvcBuilders.standaloneSetup(new ArticleController()).build();
    }
    */

    @Test
    public void saveArticle() throws Exception {
        String article = "JSON";
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders
            .request(HttpMethod.POST, "/rest/articles")
            .contentType("application/json")
            .content(article))
            .andExpect(MockMvcResultMatchers.status.isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.data.author").value("zimug"))
            .andExpect(MockMvcResultMatchers.jsonPath("$.data.reader[0].age").value(18))
            .andDo(print())
            .andReturn();
        mvcResult.getResponse().setCharacterEncoding("UTF-8");
        log.info(mvcResult.getResponse().getContentAsString());
    }
}

 Mock Service打桩设置条件(当执行Service的a方法 时去模拟对象行为)

1.真实对象的行为是不确定的(例如,当前的时间或当前的温度);
2.真实对象的行为很难触发(例如,网络错误);
3.真实对象速度很慢(例如,一个完整的教据库,在测试之前可能需要初始化);
4.真实对象可能还不存在(例如,其他程序员还未完成工作);
5.真实对象可能包含不能用作测试的信息(高度保密信息等)和方法。
等等

 Mock测试实例代码

@Slf4j
@AutoConfigureMockMvc
@SpringBootTest
@ExtendWith(SpringExtension.class)
public class Test 
{
    //mock对象
    @Resource
    private static MockMvc mockMvc;

    @MockBean//模拟注入
    private ArticleService articleService;

    /*
    @BeforeAll
    static void setUP() {
        mockMvc = MockMvcBuilders.standaloneSetup(new ArticleController()).build();
    }
    */

    @Test
    public void saveArticle() throws Exception {
        String article = "JSON";

        ObjectMapper objectMapper = new ObjectMapper();
        Article articleObj = objectMapper.readValue(article, Article.class);
        //打桩(意思是程序中有调用saveArticle方法时,模拟返回ok)
        when(articleService.saveArticle(articleObj)).thenReturn("ok");//1这个和下面(.andExpect(MockMvcResultMatchers.jsonPath("$.data").value("ok")))必须返回一致,否则失败

        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders
            .request(HttpMethod.POST, "/rest/articles")
            .contentType("application/json")
            .content(article))
            .andExpect(MockMvcResultMatchers.jsonPath("$.data").value("ok1"))//断言值
            .andDo(print())
            .andReturn();
        mvcResult.getResponse().setCharacterEncoding("UTF-8");
        log.info(mvcResult.getResponse().getContentAsString());
    }
}

@RestController
@RequestMapping("/rest")
public class TestController {
  @Resource
  ArticleService articleService;
@PostMapping(
"/articles") public AjaxResponse saveArticle(@RequestBody Article article) { log.info("saveArticle: " + article); return AjaxResponse.success(articleService.saveArticle(article));//这里调用saveArticle是Mock模拟调用 } }

 

轻量级Mock测试

@AutoConfigureMockMvc
@WebMvcTest(ArticleController.class只针对这一个,不加时对所有Bean加载)
@ExtendWith(SpringExtension.class)//spring运行时环境依赖注入servlet环境

 

 

官方命名:spring-boot-starter-swagger

开发者命名:swagger-xxxx-spring-boot-starter

引入2个包

 

 
java config来配置包

 

 

 

 

 

 在插件中双击生成asciidoc生成html

 

 

 

 

 

 

 

 

 

 

 

 

OpenAPI3.0规范,Swagger3.实现, SpringDoc集成到spring中

 

 

 实现openapi3.0 引包

 

 

 

 分组需要配置类

 

 

 

 

posted on 2022-10-12 09:36  王飞侠  阅读(39)  评论(0编辑  收藏  举报

导航