springboot+swagger2的使用

swagger2 可以同步api和文档,在开发的过程中 就省略了需要写开发文档以及团队之间不必要的交接问题 自己开发过程中 其实也是比较方便测试和浏览api功能的 因为要写一个用户中心的测试 正好就用一下swagger2 配置也是比较简单的 也会有一些小的问题 记录一下配置过程和解决办法
  • 引入swagger2的依赖
   
            io.springfox
            springfox-swagger2
            2.4.0
        
        
            io.springfox
            springfox-swagger-ui
            2.4.0
        
  • 新建swagger2 配置类 内容如下
@Configuration
@EnableSwagger2
public class Swagger2 {
    /**
     * @Description:swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
     */
    @Bean
    public Docket createRestApi() {

        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.emp.usercenter.pc"))
         /*       .apis(RequestHandlerSelectors.withClassAnnotation(Controller.class))*/
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * @Description: 构建 api文档的信息
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 设置页面标题
                .title("用户中心后端api接口文档")
                // 设置联系人
                .contact(new Contact("employeeeee", "https://zhouzihao.xyz", "[email protected]"))
                // 描述
                .description("欢迎访问用户中心接口文档,这里是描述信息")
                // 定义版本号
                .version("1.0").build();
    }

}

我第一次用swagger2的时候 是横向分割的 按照不同的module来建立的项目 所以所有的controller都放在了一个包里,而这次的项目我是按照com.emp.*.controller的形式来搭建的 开始尝试使用在basepackage中这样写是行不通的 所以如果是要使用多个controller的包 可以给定位到它们的上级目录 或者是统一使用一种 controller或者restcontroller的注解,
然后通过.apis(RequestHandlerSelectors.withClassAnnotation(Controller.class))来扫描.

  • 在controller中 添加相应的api注释
@Controller
@Api(value = "用户信息查询",tags = {"用户信息的controller"})
public class CustomerController {
    @Resource
    private CustomerService customerService;

    @ApiOperation(value = "用户所有信息查询",notes = "用户信息查询接口")
    @GetMapping("index")
    private String customerIndex(Model model){
        List customerList = customerService.selectAll();
        model.addAttribute("customerList",customerList);
        return "customer/index";
    }

}
  • model中给参数添加注释 因为我是一个查询 没有参数 但是如果是查询啊 删除什么的 就需要传参 如下
@ApiModel(value = "用户对象",description = "用户实体类")
public class Customer {
    /*@ApiModelProperty(hidden = true)*/
    private String cid;

    /*@ApiModelProperty(value = "用户名",name = "username",example = "zhou",required = true)*/
    private String cname;

然后访问 你的 localhost + swagger-ui.html


springboot+swagger2的使用_第1张图片
image.png

你可能感兴趣的:(springboot+swagger2的使用)