springboot 集成 swagger 和 swagger-bootstrap-ui

1 项目集成:

第一步:pom.xml 添加相关的依赖jar包
   <!-- 升级版的swagger依赖的jar包-->

        <!-- swagger用于定义API文档 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

        <!--美化swagger-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.3</version>
        </dependency>
第二步: 创建两个相关的配置类,记得添加注解-> @Configuration 和 @EnableSwagger2
第1个配置类:
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.icitic.mc.user.services.web")) //此次每次使用须换成自己的web接口的全限定类名
                //.paths(AppUtility.isProd() ? PathSelectors.none() : PathSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("测试swagger")
                .description("展示swagger界面")
                .termsOfServiceUrl("http://localhost:9001/swagger-ui.html")
                .contact(new Contact("tina.liu", "http://localhost:9001/swagger-ui.html", "xxxxx@qq.com"))
                .version("1.0")
                .build();
    }

}

第2个配置类:
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        
        //排除静态文件
        
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

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

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

}
第三步: 查看 http://127.0.0.1:8089/doc.html

2 . swagger 相关的一些注解 及范例:

@Api(tags = "用户模块"):用在类上,说明该类的作用。
@ApiOperation:注解来给API增加方法说明。
@ApiImplicitParams : 用在方法上包含一组参数说明。
@ApiImplicitParam:用来注解来给方法入参增加说明。
@ApiResponses:用于表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息

  • code:数字,例如400
  • message:信息,例如"请求参数没填好"
  • response:抛出异常的类
    @ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)
  • @ApiModelProperty:描述一个model的属性
    注意:@ApiImplicitParam的参数说明:

paramType:指定参数放在哪个地方
header:请求参数放置于Request Header,使用@RequestHeader获取
query:请求参数放置于请求地址,使用@RequestParam获取
path:(用于restful接口)-->请求参数的获取:@PathVariable
body:(不常用)
form(不常用)
name:参数名
dataType:参数类型
required:参数是否必须传 true | false
value:说明参数的意思
defaultValue:参数的默认值

(1)Model (数据库表的映射对象,及实体类)中使用 Swagger 注解


@ApiModel(value = "UserEntity", description = "用户对象")
public class UserEntity implements Serializable{

    @ApiModelProperty(value ="用户id",name="id",dataType="Long",required = false,example = "1",hidden = false )
    private Long id;

    @ApiModelProperty(value ="用户名",name="userName",dataType="String",required = false,example = "关羽" )
    private String userName;

    @ApiModelProperty(value ="用户性别",name="userSex",dataType="String",required = false,example = "男" )
    private String userSex;
}

(2) web层API接口(controller类) 中使用swagger注解

@RestController
@Slf4j
@RequestMapping(value = "/v1/service")
@RefreshScope // 支持nacos配置动态刷新的功能
@Api(tags = "用户模块")

public class UserApi {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "分页查询")
    @ApiImplicitParams(value ={
            @ApiImplicitParam(name = "page",value="当前页码",required = false,dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name="size",value = "每页大小",required = false,dataType = "Integer",paramType = "query"),
    } )
    @GetMapping
    public Response getUserByPage(UserPageable userPageable){
        return userService.getUserByPage(userPageable);
    }

    // 根据Id查询用户的信息
    @ApiOperation(value = "用户查询",notes ="用户查询")
    @ApiImplicitParam(name = "id",value = "id",required = true
            ,dataType = "Long",paramType = "path")
    @GetMapping(value = "/{id}")
    public Response getUserById(@PathVariable Long id) {
        return Response.success().data("data",userService.getUserById(id));
    }

    //添加用户的接口
    @ApiOperation(value = "添加用户",notes = "添加用户")
    @ApiImplicitParam(name="request",value = "新增用户参数",required = true,dataType = "UserCreateRequest",paramType = "body")
    @PostMapping
    public Response createUser(@RequestBody UserCreateRequest request){
        return userService.save(request);
    }

    //根据ID删除用户的接口
    @ApiOperation(value = "根据ID删除用户",notes = "根据ID删除用户")
    @ApiImplicitParam(name ="id",value = "id",required = true,dataType = "Long",paramType = "path")
    @DeleteMapping(value = "/{id}")
    public Response deleteUserById(@PathVariable Long id){

        return userService.deleteUserById(id);
    }

    //修改用户的接口
    @ApiOperation(value = "修改用户")
    @ApiImplicitParam(name = "request",value = "修改用户的参数",required = true,dataType = "UserUpdateRequest",paramType = "body")
    @PutMapping(value = "/{id}")
    public Response updateUser(@RequestBody UserUpdateRequest request , @PathVariable Long id){
        return userService.updateUser(request,id);
    }

    //用户登陆的接口
    @ApiOperation(value = "用户登陆",notes = "用户登陆")
    @ApiImplicitParam(name="request",value = "用户登陆的参数",required = true,dataType = "UserLoginRequest",paramType = "body")
    @PostMapping(value = "/login")
    public Response Login(@RequestBody UserLoginRequest request){
       User user  =  userService.login(request);
       if(user != null){
           return Response.fail().data("token",TokenUtil.getToken());
       }
        return Response.success().data("token",null);
    }

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 介绍 什么是Swagger Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风...
    TurboSnail阅读 3,593评论 0 4
  • 简介 Swagger 是最流行的 API 开发工具,它遵循 OpenAPI Specification(OpenA...
    LittleJessy阅读 32,288评论 0 15
  • 在软件开发行业,管理文档是件头疼的事。不是文档难于撰写,而是文档难于维护,因为需求与代码会经常变动,尤其在采用敏捷...
    杨梅泡酒阅读 46,578评论 12 56
  • 今天文案学习的打卡作业是一份推销自己的自我介绍。自听完课到拿来作业,我一直都在思考——“卖点”“亮点”。像我这样一...
    婆妈读书阅读 219评论 0 1
  • 5. 气势汹汹拉开大门,水瓶不负众望的被绊倒了。剩下11个拿着乱七八糟东西的星座惊恐的看着水瓶……前面的又一扇...
    埙与陶笛阅读 750评论 0 3

友情链接更多精彩内容