码上敲享录 > springcloud开发经验分享 > Springboot整合Swagger2,很简单

Springboot整合Swagger2,很简单

上一章章节目录下一章 2023-01-08已有774人阅读 评论(0)

Springboot整合Swagger2,很简单

解决方法:

1:在springboot启动类配置如下,方便启动项目直接看到路径,点击可直接测试

@Slf4j

@SpringBootApplication

public class SpbthymyibatisApplication {


   public static void main(String[] args) throws UnknownHostException {

       ConfigurableApplicationContext application =SpringApplication.run(SpbthymyibatisApplication.class, args);

       Environment env = application.getEnvironment();

       String ip = InetAddress.getLocalHost().getHostAddress();

       String port = env.getProperty("server.port");

       String path = env.getProperty("server.servlet.context-path");

       log.info("\n----------------------------------------------------------\n\t" +

               "Application Jeecg-Boot is running! Access URLs:\n\t" +

               "Local: \t\thttp://localhost:" + port + path + "/\n\t" +

               "External: \thttp://" + ip + ":" + port + path + "/\n\t" +

               "swagger-ui: \thttp://" + ip + ":" + port + path + "/swagger-ui.html\n\t" +

               "Doc: \t\thttp://" + ip + ":" + port + path + "/doc.html\n" +

               "----------------------------------------------------------");

   }


}




2:Swagger配置类

package com.example.config;


import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;

import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;

import springfox.documentation.builders.ParameterBuilder;

import springfox.documentation.builders.PathSelectors;

import springfox.documentation.builders.RequestHandlerSelectors;

import springfox.documentation.schema.ModelRef;

import springfox.documentation.service.ApiInfo;

import springfox.documentation.service.Parameter;

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;


/**

* @Author dell

* @create 2022/11/8

*/

@Slf4j

@Configuration

@EnableSwagger2

public class SwaggerConfig {


   /**

    * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等

    *

    * @return Docket

    */

   @Bean

   public Docket createRestApi() {

       ParameterBuilder tokenPar = new ParameterBuilder();

       List<Parameter> pars = new ArrayList<>();

       tokenPar.name("X-Access-Token").description("AccessToken令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();

       pars.add(tokenPar.build());

       return new Docket(DocumentationType.SWAGGER_2)

               .apiInfo(apiInfo())

               .select()

               //扫描方式1,此包路径下的类,才生成接口文档

               .apis(RequestHandlerSelectors.basePackage("com.example.controller"))

               //扫描方式2:扫描所有有类注解的api,加了Api注解的类,才生成接口文档

               .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))

               //扫描方式3:扫描所有有方法注解的ApiOperation,用这种方式更灵活,才生成接口文档

               .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))

               // 扫描方式4:扫描所有

               .paths(PathSelectors.any())

               .build()

               .globalOperationParameters(pars);

   }


   /**

    * api文档的详细信息函数,注意这里的注解引用的是哪个

    *

    * @return

    */

   private ApiInfo apiInfo() {

       return new ApiInfoBuilder()

               .title("Spbthymyibatis 后台服务API接口文档")

               .description("restful 风格接口")

               .termsOfServiceUrl("http://www.baidu.com/")

               .version("1.0")

               .build();

   }

}



3:在yaml或者properties文件配置

server.port=8888

server.servlet.context-path=/spbthymeibatis

#注意必须要有此行ant匹配,不然swagger启动报错

spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER

#扫描实体类

mybatis.type-aliases-package=com.example.entity

#扫描映射文件

mybatis.mapper-locations: classpath:mapper/*.xml


#配置数据库

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false&autoReconnect=true&failOverReadOnly=false&autoReconnectForPools=true

spring.datasource.username=root

spring.datasource.password=root


#过滤静态资源

spring.mvc.static-path-pattern=/**


#指定系统直接访问路径

spring.web.resources.static-locations = classpath:/templates/,classpath:/META-INF/resources/,classpath:/resources/

#热部署:修改后台文件保存后自动重启

#spring.devtools.restart.enabled=true


#Messages资源信息

#spring.messages.basename=messages


#关闭thymeleaf缓存 开发时使用 否则没有实时画面

spring.thymeleaf.cache=false



4: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 https://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.6.1</version>

       <relativePath/> <!-- lookup parent from repository -->

   </parent>

   <groupId>com.example</groupId>

   <artifactId>spbthymyibatis</artifactId>

   <version>0.0.1-SNAPSHOT</version>

   <packaging>war</packaging>


   <name>spbthymyibatis</name>

   <description>Demo project for Spring Boot</description>

   <properties>

       <java.version>1.8</java.version>

   </properties>

   <dependencies>

       <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-jdbc</artifactId>

       </dependency>

       <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-thymeleaf</artifactId>

       </dependency>

       <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-web</artifactId>

       </dependency>

       <dependency>

           <groupId>org.mybatis.spring.boot</groupId>

           <artifactId>mybatis-spring-boot-starter</artifactId>

           <version>2.2.0</version>

       </dependency>


       <dependency>

           <groupId>mysql</groupId>

           <artifactId>mysql-connector-java</artifactId>

           <scope>runtime</scope>

       </dependency>

       <dependency>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-test</artifactId>

           <scope>test</scope>

       </dependency>

       

       <!-- Swagger API文档 -->

       <dependency>

           <groupId>io.swagger</groupId>

           <artifactId>swagger-annotations</artifactId>

           <version>1.5.21</version>

       </dependency>

       <dependency>

           <groupId>io.swagger</groupId>

           <artifactId>swagger-models</artifactId>

           <version>1.5.21</version>

       </dependency>

       

       <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>

       <dependency>

           <groupId>com.github.xiaoymin</groupId>

           <artifactId>swagger-bootstrap-ui</artifactId>

           <version>1.9.3</version>

       </dependency>

       <dependency>

           <groupId>io.springfox</groupId>

           <artifactId>springfox-bean-validators</artifactId>

           <version>2.9.2</version>

       </dependency>


       <!-- Lombok -->

       <dependency>

           <groupId>org.projectlombok</groupId>

           <artifactId>lombok</artifactId>

       </dependency>



   </dependencies>


   <build>

       <plugins>

           <plugin>

               <groupId>org.apache.maven.plugins</groupId>

               <artifactId>maven-resources-plugin</artifactId>

               <version>3.1.0</version><!--亲测:3.1.0和2.4.3都可以。-->

           </plugin>

       </plugins>

   </build>


</project>




5:将接口文档暴露在外网会出现一定的安全问题,此时我们需要给Swagger文档配置登录密码


5.1:添加依赖,已经添加过

<dependency>

   <groupId>com.github.xiaoymin</groupId>

   <artifactId>swagger-bootstrap-ui</artifactId>

   <version>1.9.3</version>

</dependency>


5.2:更新配置类,再配置类加上@EnableSwaggerBootstrapUI

@Configuration

@EnableSwagger2

@EnableSwaggerBootstrapUI //添加注解

public class SwaggerConfig {

}



5.3:在yaml或者properties文件添加

# true为启动用密码,false为关闭密码

swagger.basic.enable=true

swagger.basic.username=admin

swagger.basic.password=admin



6、Swagger常用注解

//控制类上

@Api(tags = “控制类”)


//控制类的方法上

@ApiOperation(value = “方法”, notes = “方法”)


//控制类方法参数上使用

@ApiParam(value = “参数”, allowableValues = “range[1,10]”, required = true)


//控制类方法上这是请求的@ApiImplicitParams、@ApiImplicitParam

@ApiImplicitParams({

@ApiImplicitParam(name=“phonenum”,value=“手机号”,required=true,paramType=“query”,dataType=“Long”),

@ApiImplicitParam(name=“password”,value=“密码”,required=true,paramType=“query”,dataType=“String”),

@ApiImplicitParam(name=“age”,value=“年龄”,required=true,paramType=“query”,dataType=“Integer”,dataType=“Long”)

})


//控制类方法上这是响应的@ApiResponses、@ApiResponse

@ApiResponses({

@ApiResponse(code = 200, message = “请求成功”),

@ApiResponse(code = 400, message = “请求参数没填好”),

@ApiResponse(code = 404, message = “请求路径没有或页面跳转路径不对”)

})


//实体类,dot,vo,entity上

@ApiModel(value=“对象”, description=“对象”)


//实体类,dot,vo,entity的属性上,example 是默认值

@ApiModelProperty(value = “属性” ,required = true,example = “0”)


向大家推荐《Activiti工作流实战教程》:https://xiaozhuanlan.com/activiti
0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交