SpringBoot整合Swagger API接口文档

1.在pom.xml引入依赖

        <dependency><!--添加Swagger依赖 -->
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency><!--添加Swagger-UI依赖 -->
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

2.进行配置

/**
 * swagger配置类
 * http://localhost:8080/swagger-ui.html
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig  {

    /**
     * 配置api文档
     */
    @Bean
    public Docket configApiDocs() {
        List<ResponseMessage> responseMessageList = new ArrayList<>();
        responseMessageList.add(new ResponseMessageBuilder().code(400).message("错误请求").build());
        responseMessageList.add(new ResponseMessageBuilder().code(401).message("未授权").build());
        responseMessageList.add(new ResponseMessageBuilder().code(403).message("禁止").build());
        responseMessageList.add(new ResponseMessageBuilder().code(404).message("未找到").build());
        responseMessageList.add(new ResponseMessageBuilder().code(500).message("服务器内部错误").build());

        return new Docket(DocumentationType.SWAGGER_2)
                .globalResponseMessage(RequestMethod.GET, responseMessageList)
                .globalResponseMessage(RequestMethod.POST, responseMessageList)
                .globalResponseMessage(RequestMethod.PUT, responseMessageList)
                .globalResponseMessage(RequestMethod.DELETE, responseMessageList)
                .apiInfo(new ApiInfoBuilder()
                        .title("XXAPI文档")
                        .description("本文档描述XX相关API")
                        .contact(new Contact(null, null,null))
                        .build())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.seckill"))//包名
                .paths(PathSelectors.any())
                .build();
    }

}

3.使用注解

3.1 model类

@ApiModel("管理员")
public class AdminVo {
    @ApiModelProperty("")
    private Integer id;

    @ApiModelProperty("管理员账号")
    private String adminName;

    @ApiModelProperty("管理员密码")
    private String adminPassword;

    @ApiModelProperty("管理员角色Id")
    private Integer roleId;
    @JsonIgnore//返回的json没有这个元素
    private Integer offset;
    @JsonIgnore
    private Integer limit;

}

3.2 controller


@Api(tags = "管理员管理")
@RestController
@RequestMapping(Namespace.API)
public class AdminApi {
    @Resource
    IAdminService iAdminService;
    @Resource
    private HttpServletResponse response;
    @ApiOperation("添加管理员")
    @PreAuthorize("hasRole('ADD_ADMIN')")
    @PostMapping(Namespace.ADMIN)
    public AdminVo insert(
            @RequestParam @ApiParam(value = "管理员账号", required = true) String adminName,
            @RequestParam @ApiParam(value = "管理员密码", required = true) String adminPassword,
            @RequestParam @ApiParam(value = "管理员角色Id", required = true) Integer roleId
    ) {

    }

    @ApiOperation("修改管理员密码或管理员角色Id")
    @PutMapping(Namespace.ADMIN + "/{id}")
    @PreAuthorize("hasRole('UPDATE_ADMIN')")
    public String update(
            @PathVariable @ApiParam(value = "id") Integer id,
            @RequestParam(required = false) @ApiParam(value = "管理员密码") String adminPassword,
            @RequestParam(required = false) @ApiParam(value = "管理员角色Id") Integer roleId
    ) {

    }
    @ApiOperation("删除管理员")
    @DeleteMapping(Namespace.ADMIN+ "/{id}" )
    @PreAuthorize("hasRole('DELETE_ADMIN')")
    public String delete(
            @PathVariable @ApiParam(value = "id", required = true) Integer id
    ) {

    }
    @ApiOperation("查询管理员列表")
    @GetMapping(Namespace.ADMIN)
    @PreAuthorize("hasRole('SELECT_ADMIN')")
    public List<AdminVo> list(
            @RequestParam(defaultValue = "0") @ApiParam(value = "偏移量") Integer offset,
            @RequestParam(defaultValue = "10") @ApiParam(value = "限制") Integer limit) {
 
    }
}

4.效果展示

5.常见问题

5.1 请求不到swagger-ui.html

No mapping found for HTTP request with URI [/swagger-ui.html] in DispatcherServlet with name ‘dispatcherServlet’

这个错误,是因为静态资源路径映射问题导致,SpringBoot自动配置本身并不会把/swagger-ui.html这个路径映射到对应的目录META-INF/resources/下面。我们加上这个映射即可。

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

5.2 整合Spring Security时,请求不到swagger-ui.html

swagger的资源被拦截了。

需要进行过滤。

            .antMatchers(
                    "/v2/api-docs",
                    "/swagger-resources/**",
                    "/swagger-ui.html",
                    "/webjars/**").permitAll()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值