springboot + security + swagger+Knife4j springboot整合swagger swagger优化,接口文档生成多包扫描,security免登陆 生成接口文档

首先项目使用SpringBoot框架,swagger接口文档,下面上代码,从新建一个项目开始搭起。

参考文档:

swagger文档
Swagger注解说明
knife4j 参考文档

新建SpringBoot项目

POM文件配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.cn.binglong</groupId>
    <artifactId>SwaggerDemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <java.version>1.8</java.version>
    </properties>

<dependencies>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>
</dependencies>

<build>
<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
</plugins>
</build>

</project>
控制层
package com.cn.binglong.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 类 名: HelloController
 * 描 述:
 * 作 者: binglong180
 * 创 建: 2020-07-07 14:40
 * 邮 箱: binglong172@163.com
 */

@RestController
public class HelloController {
    @RequestMapping("/")
    public String index() {
        return "Greetings from Spring Boot!";
    }
}

启动类
package com.cn.binglong;

import com.cn.binglong.bean.Person;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Arrays;

/**
 * 类 名: TestMain
 * 描 述:
 * 作 者: binglong180
 * 创 建: 2020-07-06 15:57
 * 邮 箱: binglong172@163.com
 */

@SpringBootApplication
public class  Application{



    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {

            System.out.println("Let's inspect the beans provided by Spring Boot:");

            String[] beanNames = ctx.getBeanDefinitionNames();
            Arrays.sort(beanNames);
            for (String beanName : beanNames) {
                System.out.println(beanName);
            }

        };
    }
}

启动项目

在这里插入图片描述
在这里插入图片描述

引入Swagger pom 文件
    <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>
创建SwaggerConfig 配置Swagger

host 修改request ip或域名
pathMapping 修改 request url

package com.cn.binglong.cfg;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * 类 名: SwaggerConfig
 * 描 述:
 * 作 者: binglong180
 * 创 建: 2020-07-08 12:22
 * 邮 箱: binglong172@163.com
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .host("localhost:8080")
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.cn.binglong.controller"))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("SpringBoot整合Swagger")
                        .description("SpringBoot整合Swagger,详细信息......")
                        .version("9.0")
                        .contact(new Contact("binglong180","www.binglong180.com","binglong172@163.com"))
                        .license("Swagger文档")
                        .licenseUrl("https://swagger.io/docs/specification/2-0/basic-structure/")
                        .build());
    }
}
控制层多包扫描
package com.cn.binglong.cfg;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * 类 名: SwaggerConfig
 * 描 述:
 * 作 者: binglong180
 * 创 建: 2020-07-08 12:22
 * 邮 箱: binglong172@163.com
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    // 定义分隔符
    private static final String splitor = ";";
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .host("localhost:8080")
                .pathMapping("/")
                .select()
              /*  .apis(RequestHandlerSelectors.basePackage("com.cn.binglong.controller"))*/
                .apis(basePackage("com.cn.binglong.controller"
                        + splitor +
                        "com.cn.binglong.controller2"))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("SpringBoot整合Swagger")
                        .description("SpringBoot整合Swagger,详细信息......")
                        .version("9.0")
                        .contact(new Contact("binglong180","www.binglong180.com","binglong172@163.com"))
                        .license("Swagger文档")
                        .licenseUrl("https://swagger.io/docs/specification/2-0/basic-structure/")
                        .build());
    }


    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        return input -> {
            // 循环判断匹配
            for (String strPackage : basePackage.split(splitor)) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }
}
Swagger注解说明
@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:用在属性上,描述响应类的属性
访问Swagger
http://localhost:8080/swagger-ui.html#/
加入Swagger 效果

在这里插入图片描述

不同环境下Swagger启用禁用

使用@Profile({}) 把相应的环境配置加入就表示在该环境下启用swagger,否则将会被禁用

@Configuration
@EnableSwagger2
@Profile({"dev"})
public class SwaggerConfig {
    // 定义分隔符
    private static final String splitor = ";";
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .host("localhost:8080")
                .pathMapping("/")
                .select()
              /*  .apis(RequestHandlerSelectors.basePackage("com.cn.binglong.controller"))*/
                .apis(basePackage("com.cn.binglong.controller"
                    /*    + splitor +
                        "com.cn.binglong.controller2"*/))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("SpringBoot整合Swagger")
                        .description("SpringBoot整合Swagger,详细信息......")
                        .version("1.0")
                        .contact(new Contact("binglong180","www.binglong180.com","binglong172@163.com"))
                        .license("Swagger文档")
                        .licenseUrl("https://swagger.io/docs/specification/2-0/basic-structure/")
                        .build());
    }
Security 中整合swagger或其他安全中要对相应路径及资源放行
		web.ignoring().antMatchers("/swagger/**")
				.antMatchers("/swagger-ui.html")
				.antMatchers("/webjars/**")
				.antMatchers("/v2/**")
				.antMatchers("/swagger-resources/**");
整合 Knife4j pom文件加入
      <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-spring-boot-starter</artifactId>
        <version>2.0.4</version>
      </dependency>
访问http://localhost:8080/doc.html

在这里插入图片描述

注意事项
  • knife4j 参考文档 https://doc.xiaominfo.com/
  • 安全框架要放行 springSecurity 或 shiro
		web.ignoring().antMatchers("/swagger/**")
				.antMatchers("/swagger-ui.html")
				.antMatchers("/webjars/**")
				.antMatchers("/v2/**")
        .antMatchers("/v2/api-docs-ext/**")
				.antMatchers("/swagger-resources/**")
        .antMatchers("/doc.html");

/doc.html 和 /v2/api-docs-ext 是Knife4j 的其他是swagger的

  • 配置 swagger knife4j 访问静态资源路径
@Configuration
public class SwaggerWebMvcConfig 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/");
    }
}
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个用于创建独立的、基于生产级别的Spring应用程序的框架。它简化了Spring应用程序的配置和部署过程,并提供了一套强大的开发工具和约定,使开发人员能够更专注于业务逻辑的实现。 MyBatis Plus是MyBatis的增强工具,它提供了一系列的便利功能和增强特性,使得使用MyBatis更加简单和高效。它包括了代码生成器、分页插件、逻辑删除、乐观锁等功能,可以大大提高开发效率。 Redis是一个开源的内存数据库,它支持多种数据结构,如字符串、哈希、列表、集合、有序集合等。Redis具有高性能、高可用性和可扩展性的特点,常用于缓存、消息队列、分布式锁等场景。 Driver是指数据库驱动程序,它是用于连接数据库和执行SQL语句的软件组件。在Spring Boot中,我们可以通过配置数据源和引入相应的数据库驱动程序来实现与数据库的交互。 Knife4j是一款基于Swagger的API文档生成工具,它提供了更加美观和易用的界面,可以方便地查看和测试API接口。 Swagger是一套用于设计、构建、文档化和使用RESTful风格的Web服务的工具。它可以自动生成API文档,并提供了交互式的界面,方便开发人员进行接口测试和调试。 JWT(JSON Web Token)是一种用于身份验证和授权的开放标准。它通过在用户和服务器之间传递加密的JSON对象来实现身份验证和授权功能,避了传统的基于Session的身份验证方式带来的一些问题。 Spring SecuritySpring提供的一个安全框架,它可以集成到Spring Boot应用程序中,提供身份验证、授权、攻击防护等安全功能。通过配置Spring Security,我们可以实现对API接口的访问控制和权限管理。 关于Spring Boot + MyBatis Plus + Redis + Driver + Knife4j + Swagger + JWT + Spring Security的Demo,你可以参考以下步骤: 1. 创建一个Spring Boot项目,并引入相应的依赖,包括Spring Boot、MyBatis Plus、Redis、数据库驱动程序等。 2. 配置数据源和数据库驱动程序,以及MyBatis Plus的相关配置,如Mapper扫描路径、分页插件等。 3. 集成Redis,配置Redis连接信息,并使用RedisTemplate或者Jedis等工具类进行操作。 4. 集成Knife4jSwagger,配置Swagger相关信息,并编写API接口文档。 5. 集成JWT和Spring Security,配置安全相关的信息,如登录认证、权限管理等。 6. 编写Controller层的代码,实现具体的业务逻辑。 7. 运行项目,通过Swagger界面进行接口测试。 希望以上内容对你有帮助!如果还有其他问题,请继续提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值