SpringBoot初级开发--加入Swagger展现接口文档(5)


  Swagger 是一个规范且完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。作为web开发,它已经成了接口文档服务的代名词了。现在很多协作型项目,都用它生成api文档,让大家能够很好的协作开发。紧接上一章,我们在工程中接入Swagger来接生成接口API服务。

1.在pom.xml加入依赖

  
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-boot-starterartifactId>
            <version>3.0.0version>
        dependency>

2.在application.properties加入关键属性

因为Springfox使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher,所以这里要修改一下。

spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER

3.在源代码中加入api注解

package com.example.firstweb.controller;


import com.example.firstweb.model.po.WelcomePo;
import com.example.firstweb.model.vo.WelcomeVo;
import com.example.firstweb.service.WelcomeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@Api(value = "welcome controller", tags = "欢迎界面")
public class Welcome {

    @Autowired
    private WelcomeService welcomeService;

    @GetMapping("/welcomeindex")
    @ApiOperation("欢迎首页的方法1")
    public ModelAndView welcomeIndex(){

        ModelAndView view = new ModelAndView("welcomeindex");


        WelcomePo wpo= welcomeService.getWelcomInfo();

        WelcomeVo wvo= new WelcomeVo();

        BeanUtils.copyProperties(wpo, wvo);

        view.addObject("welcomedata", wvo);

        return view;
    }
    @GetMapping("/welcomeindex2")
    @ApiOperation("欢迎首页的方法2")
    public void welcomeIndex2(@ApiParam("定制欢迎词") String test){

    }
}

通过浏览器访问http://localhost:8088/swagger-ui/index.html
可以看到接口api服务了
SpringBoot初级开发--加入Swagger展现接口文档(5)_第1张图片
这里有一份Swagger注解的使用说明,可以参考一下
SpringBoot初级开发--加入Swagger展现接口文档(5)_第2张图片
举两个例子标明使用方法

@ApiOperation(value = "新增用户")
@ApiResponses({ @ApiResponse(code = 200, message = "OK", response = UserDto.class) })
@PostMapping("/user")
public UserDto addUser(@RequestBody AddUserParam param) {
    System.err.println(param.getName());
    return new UserDto();
}
@Data
@ApiModel(value = "com.biancheng.auth.param.AddUserParam", description = "新增用户参数")
public class AddUserParam {

    @ApiModelProperty(value = "ID")
    private String id;

    @ApiModelProperty(value = "名称")
    private String name;

    @ApiModelProperty(value = "年龄")
    private int age;
}

程序源码可以在这里获得链接: https://pan.baidu.com/s/1d1zndKLcGSYAGGGcSGXRjg 提取码: ue7i

你可能感兴趣的:(JAVA,springboot,spring,boot,后端,java,spring)