SpringBoot 基础Swagger增强版

Springboot 2 以上版 集成 swagger2

swagger自带的ui挺弟弟的,网上看到了大佬写的不错.

增强版来源 https://doc.xiaominfo.com/guide/useful.html

1.依赖配置

 <dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger2</artifactId>
      <version>2.9.2</version>
</dependency>
<dependency>
      <groupId>com.github.xiaoymin</groupId>
      <artifactId>swagger-bootstrap-ui</artifactId>
      <version>1.9.6</version>
</dependency>

注:如果和你的springboot 核心依赖冲突 导入以下依赖

<dependency>
   <groupId>org.springframework.plugin</groupId>
    <artifactId>spring-plugin-core</artifactId>
    <version>1.2.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.plugin</groupId>
    <artifactId>spring-plugin-metadata</artifactId>
    <version>1.2.0.RELEASE</version>
</dependency>

2.配置config


其实配置 和swagger配置一模一样,增强版本有些其他的 功能。

@Configuration
@EnableSwagger2
//使用增强功能
@EnableSwaggerBootstrapUI 
public class SwaggerConfig {

    /** 扫包根路径 **/
    //默认业务代码扫包路径
    private final String defaultPackage = "com.xxxxx.xxx";
    private final String defaultGroupName = "业务代码组";
    //自定义扫包路径(我定义了一个系统级别代码)
    private final String systemPackage= "com.xxxxx.xxx";
    private final String systemGroupName = "系统管理组";
    //标题
    private final String title = "xxxxx系统";
     //描述
    private final String description = "xxxxm描述";
    //termsOfServiceUrl
    private final String termsOfServiceUrl = "xxxxx";
    private final String version = "1.0";
    //消息体对象
    private final  String resp = "ResponseMsg";


    @Bean(value = "defaultApi")
    public Docket createRestApi() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .groupName(defaultGroupName)
                .select()
                .apis(RequestHandlerSelectors.basePackage(defaultPackage))
                .paths(PathSelectors.regex("/api.*"))
                .build();
        return buildDefaultApi(docket);
    }
    @Bean(value = "systemApi")
    public Docket systemApi() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .groupName(systemGroupName)
                .select()
                .apis(RequestHandlerSelectors.basePackage(systemPackage))
                .paths(PathSelectors.regex("/sys.*"))
                .build();
        return buildDefaultApi(docket);

    }

    /**
     * 默認配置
     * @param docket
     * @return
     */
    public Docket  buildDefaultApi(Docket docket){
        List<ResponseMessage> responseMessageList = new ArrayList<>();
        responseMessageList.add(new ResponseMessageBuilder().code(404).message("找不到资源").responseModel(new ModelRef(resp)).build());
        responseMessageList.add(new ResponseMessageBuilder().code(400).message("参数校验异常").responseModel(new ModelRef(resp)).build());
        responseMessageList.add(new ResponseMessageBuilder().code(401).message("沒有登錄憑證/授權碼過期").responseModel(new ModelRef(resp)).build());
        responseMessageList.add(new ResponseMessageBuilder().code(500).message("服务器内部错误").responseModel(new ModelRef(resp)).build());
        responseMessageList.add(new ResponseMessageBuilder().code(402).message("無效權限").responseModel(new ModelRef(resp)).build());

        docket.apiInfo(apiInfo())
                .globalResponseMessage(RequestMethod.GET, responseMessageList)
                .globalResponseMessage(RequestMethod.POST, responseMessageList)
                .globalResponseMessage(RequestMethod.PUT, responseMessageList)
                .globalResponseMessage(RequestMethod.DELETE, responseMessageList)
                .securityContexts(Lists.newArrayList(securityContext())).securitySchemes(Lists.<SecurityScheme>newArrayList(apiKey()));
        return docket;
    }


    /**
     * 登錄auto配置
     * @return
     */
    private ApiKey apiKey() {
        return new ApiKey("BearerToken", "Authorization", "header");
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("/.*"))
                .build();
    }
    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Lists.newArrayList(new SecurityReference("BearerToken", authorizationScopes));
    }

    /**
     * apiInfo 
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .termsOfServiceUrl(termsOfServiceUrl)
                .version(version)
                .contact("xxx")
                .build();
    }
}


这样就配好了,如果系统做了权限配置 开放以下路径白名单
 

/swagger-resources 
/v2/api-docs 
/v2/api-docs-ext 
/doc.html
/webjars/**

注:主页地址 api地址为 /doc.html 非 /swagger-ui.html


3.增强功能
 

3.1访问权限控制

swagger.production=true

开启生产环境,屏蔽Swagger所有资源接口,关闭皆可以访问。

3.2访问页面加权控制
 

 

## 开启Swagger的Basic认证功能,默认是false
swagger.basic.enable=true
## Basic认证用户名
swagger.basic.username=admin
## Basic认证密码
swagger.basic.password=admin.xxx

 

4.界面风格(建议直接看knife4j官网,我都是直接抄的)

 

我的欣赏水平觉得 比 原本ui好看。

 

参考资料地址 :
https://doc.xiaominfo.com  

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 基础教程(基于1.3.x-1.5.x) 快速入门 chapter1:基本项目构建(可作为工程脚手架),引入web模块,完成一个简单的RESTful API 使用Intellij中的Spring Initializr来快速构建Spring Boot/Cloud工程 工程配置 chapter2-1-1:配置文件详解:自定义属性、随机数、多环境配置等 chapter2-1-2:2.0 新特性(一):配置绑定全解析 chapter2-2-1:2.0 新特性(二):新增事件ApplicationStartedEvent Web开发 chapter3-1-1:构建一个较为复杂的RESTful API以及单元测试 chapter3-1-2:使用Thymeleaf模板引擎渲染web视图 chapter3-1-3:使用Freemarker模板引擎渲染web视图 chapter3-1-4:使用Velocity模板引擎渲染web视图 chapter3-1-5:使用Swagger2构建RESTful API chapter3-1-6:统一异常处理 chapter3-1-7:使用Java 8中LocalDate等时间日期类的问题解决 chapter3-1-8:扩展XML请求和响应的支持 数据访问 chapter3-2-1:使用JdbcTemplate chapter3-2-2:使用Spring-data-jpa简化数据访问层(推荐) chapter3-2-3:多数据源配置(一):JdbcTemplate chapter3-2-4:多数据源配置(二):Spring-data-jpa chapter3-2-5:使用NoSQL数据库(一):Redis chapter3-2-6:使用NoSQL数据库(二):MongoDB chapter3-2-7:整合MyBatis chapter3-2-8:MyBatis注解配置详解 chapter3-2-9:使用Flyway来管理数据库版本 chapter3-2-10:使用LDAP来统一管理用户信息 chapter3-2-11:Spring Boot中增强对MongoDB的配置(连接池等) 事务管理 chapter3-3-1:使用事务管理 chapter3-3-2:[分布式事务(未完成)] 其他内容 chapter4-1-1:使用@Scheduled创建定时任务 chapter4-1-2:使用@Async实现异步调用 chapter4-1-3:使用@Async实现异步调用:自定义线程池 chapter4-1-4:使用@Async实现异步调用:资源优雅关闭 chapter4-1-5:使用@Async实现异步调用:使用Future以及定义超时 日志管理 chapter4-2-1:默认日志的配置 chapter4-2-2:使用log4j记录日志 chapter4-2-3:对log4j进行多环境不同日志级别的控制 chapter4-2-4:使用AOP统一处理Web请求日志 chapter4-2-5:使用log4j记录日志到MongoDB chapter4-2-6:Spring Boot 1.5.x新特性:动态修改日志级别] 安全管理 chapter4-3-1:使用Spring Security chapter4-3-2:[使用Spring Session(未完成)] 缓存支持 chapter4-4-1:注解配置与EhCache使用 chapter4-4-2:使用Redis做集中式缓存 邮件发送 chapter4-5-1:实现邮件发送:简单邮件、附件邮件、嵌入资源的邮件、模板邮件 消息服务 chapter5-1-1:[JMS(未完成)] chapter5-2-1:Spring Boot中使用RabbitMQ 其他功能 chapter6-1-1:使用Spring StateMachine框架实现状态机 Spring Boot Actuator监控端点小结 在传统Spring应用中使用spring-boot-actuator模块提供监控端点 Spring Boot应用的后台运行配置 Spring Boot自定义Banner Dubbo进行服务治理 chapter9-2-1:Spring Boot中使用Dubbo进行服务治理 chapter9-2-2:Spring Boot与Dubbo中管理服务依赖
Spring Boot是一款非常流行的Java Web开发框架,它的特点是快速、简单、灵活,使得开发者能够快速构建出高质量的应用程序。Swagger是一个流行的开放API框架,它可以帮助开发者更加容易地构建和文档化RESTful Web服务。在本文中,我们将介绍如何在Spring Boot中使用Swagger。 1. 添加Swagger依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.8.0</version> </dependency> ``` 2. 配置Swagger 在Spring Boot的配置类中添加以下配置: ``` @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo")) .paths(PathSelectors.any()) .build(); } } ``` 其中,`@EnableSwagger2`注解启用Swagger,`Docket`对象用于配置Swagger。 3. 测试Swagger 在应用程序启动后,访问`http://localhost:8080/swagger-ui.html`即可看到Swagger的UI界面,其中包含了我们所有的API接口,可以方便地测试和调用。 4. 配置Swagger的API信息 我们可以通过在`Docket`对象上添加一些配置信息来增强Swagger的功能。例如,我们可以添加API文档的标题、描述、版本等信息: ``` @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot REST API") .description("Example REST API using Spring Boot and Swagger") .version("1.0.0") .build(); } ``` 5. 配置Swagger的安全认证 如果我们的API需要进行安全认证,我们可以在`Docket`对象上添加一些安全认证的配置信息。例如,我们可以添加基于Token的认证: ``` @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo")) .paths(PathSelectors.any()) .build() .securitySchemes(Arrays.asList(apiKey())) .securityContexts(Arrays.asList(securityContext())) .apiInfo(apiInfo()); } private ApiKey apiKey() { return new ApiKey("Token", "token", "header"); } private SecurityContext securityContext() { return SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.any()) .build(); } List<SecurityReference> defaultAuth() { AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; return Arrays.asList( new SecurityReference("Token", authorizationScopes)); } ``` 其中,`apiKey()`方法用于定义Token的名称、参数名和位置,`securityContext()`方法用于定义安全上下文,`defaultAuth()`方法用于定义安全引用。这些配置信息将被用于生成Swagger的安全文档。 总结 通过以上步骤,我们可以很容易地在Spring Boot中集成Swagger,使得我们的API文档更加易读、易用、易维护。当然,Swagger还有很多其他的功能和配置选项,读者可以根据自己的实际需求进行进一步的学习和探索。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值