欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

荐 springboot整合swagger2以及swagger2的介绍与Spring Security的整合使用

程序员文章站 2022-07-08 10:13:59
1、首先引入jar包io.springfoxspringfox-swagger22.9.2io.springfox

1、首先引入jar包

<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>

		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>

2、开启swagger,以及一些配置,参考地址

import com.google.common.base.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
 author: Administrator
*/
@Configuration
@EnableSwagger2
public class Swagger2 {

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("mybatis-plus and swagger2")
                .description("mybatis-plus and swagger2 结合使用")
                .termsOfServiceUrl("https://localhost:8081/")
                .version("1.0.0")
                .build();
    }


    @Bean
    public Docket createRestApi() {
        //可以控制 哪些符合条件的 接口 对外暴露文档;
        Predicate<RequestHandler> predicate = (input) -> {
            Set<String> patterns = input.getRequestMapping().getPatternsCondition().getPatterns();
            for (String cur : patterns) {
                //if (cur.startsWith("/api")) return true;
            }
            return true;
        };

        ResponseMessage responseMesssageSucc = new ResponseMessageBuilder()
                .code(0)
                .message("处理成功")
                .build();
        ResponseMessage responseMesssageFail = new ResponseMessageBuilder()
                .code(-1)
                .message("处理失败")
                .build();
        List<ResponseMessage> list = new ArrayList();
        list.add(responseMesssageSucc);
        list.add(responseMesssageFail);

        return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .globalResponseMessage(RequestMethod.POST, list)
                .apiInfo(apiInfo())
                .select()
                .apis(predicate)
                .apis(RequestHandlerSelectors.basePackage("com.example.mybatisplus.controller"))
                .paths(PathSelectors.any())
                .build();
    }

}

3、swagger访问页面配置类:Swagger2MvcConfig

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 author: Administrator
*/
@Configuration
public class Swagger2MvcConfig extends WebMvcConfigurationSupport {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/public/**").addResourceLocations("classpath:/public/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
    }
}

4、swagger的使用,访问接口文档:localhost:8080/swagger-ui.html
用户信息实体类使用swagger注解

import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * <p>
 * 
 * </p>
 *
 * @author jasonwang
 * @since 2020-07-30
 */
@ApiModel(value = "user",description = "用户信息表")
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
public class User extends Model {

    private static final long serialVersionUID = 1L;
    @ApiModelProperty(value = "用户id")
    private Integer id;
    @ApiModelProperty(value = "年龄")
    private Integer age;
    @ApiModelProperty(value = "姓名")
    private String name;
    @ApiModelProperty(value = "性别")
    private String sex;


}

请求类以及请求方法上使用swagger注解


import com.example.mybatisplus.model.auto.User;
import com.example.mybatisplus.service.IUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jasonwang
 * @since 2020-07-30
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @ApiOperation(value="获取用户详细信息", notes="根据id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
    @GetMapping("/{id}/getUser")
    public User getUser(@PathVariable int id){
        return userService.getById(id);
    }
    @ApiOperation(value="获取所有用户信息", notes="获取所有用户信息")
    @ApiImplicitParam()
    @GetMapping("/findAllUser")
    public List<User> findAllUser(){
        return userService.findAllUser();
    }
}

5、swagger2注解使用,参考地址:

@Api:用在请求的类上,表示对类的说明
    tags="说明该类的作用,可以在UI界面上看到的注解"
    value="该参数没什么意义,在UI界面上也看到,所以不需要配置"

@ApiOperation:用在请求的方法上,说明方法的用途、作用
    value="说明方法的用途、作用"
    notes="方法的备注说明"

@ApiImplicitParams:用在请求的方法上,表示一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:参数类型,默认String,其它值dataType="Integer"       
        defaultValue:参数的默认值

@ApiResponses:用在请求的方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类

@ApiModel:用于响应类上,表示一个返回响应数据的信息
            (这种一般用在post创建的时候,使用@RequestBody这样的场景,
            请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModelProperty:用在属性上,描述响应类的属性

6、整合 Spring Security

 // 配置权限豁免,才能正常访问 localhost:8080/swagger-ui.html
                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/v2/api-docs").permitAll()

本文地址:https://blog.csdn.net/wjs040/article/details/107693718