SpringBoot集成Swagger

目录

新建项目

hello

导包

配置类

最基础,相当于所有都是默认的。

根据环境选择是否启用swagger

配置:作者信息、分组、扫描位置、过滤扫描位置、是否启用。

配置:实体类

添加注释

报错的解决

1. 弹框报错

新建项目之引入两个包,无法添加@Api、@ApiModel注解


新建项目

 

新建成功以后,先要确定一件事。

maven的安装位置、仓库位置是默认还是自己更改过的?

如果是默认。新建项目到此结束。

否则继续。

 

设置完以后。右下角会出现这个弹框

选择自动导入

到此新建项目结束。

hello

新建controller层,写HelloController类,

代码:

package com.test.sprinbootswagger2.controller;

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

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }

}

确保是这个项目的启动类,点击启动

访问hello:http://localhost:8080/hello

前端接收到hello。

到此hello完成

导包

百度搜索maven

点第一个。

或者直接进入:https://mvnrepository.com/

搜索:springfox-swagger

 

右击3、4的红框,选择新标签页打开。

选择版本。可以选择使用最多的版本,也可以选其他。我选的是最新。

单击,会直接把坐标复制到剪切板。

回到pom.xml,把两个包都引入

 

访问swagger2的默认地址:http://localhost:8080/swagger-ui.html

出现错误提示框,表示swagger2引入成功。

 

配置类

 

新建包:config

新建类:SwaggerConfig

配置的什么,在注释里边写的很清楚。

最基础,相当于所有都是默认的。

package com.test.sprinbootswagger2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

// 标识配置类
@Configuration
// 开启swagger
@EnableSwagger2
public class SwaggerConfig {

// 配置swagger的Docket实例
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2);
    }

}

效果如图

根据环境选择是否启用swagger

配置项目多环境:

  • 默认:application.properties
    • 选择项目启用开发环境
      spring.profiles.active=dev

       

  • 项目开发环境:application-dev.properties
    • 配置端口
      server.port=8080
      

       

  • 项目发布环境:application-pro.properties
    • 配置端口
      server.port=8081
      

       

配置类:SwaggerConfig,设定开发(dev)环境启用swagger

package com.test.sprinbootswagger2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

// 标识配置类
@Configuration
// 开启swagger
@EnableSwagger2
public class SwaggerConfig {

    // 配置swagger的Docket实例
    @Bean
    public Docket docket(Environment environment){
        // 设置要显示的swagger环境
        Profiles profiles =Profiles.of("dev");
        // 通过environment.acceptsProfiles判断自己是否在设定的环境中
        boolean flag = environment.acceptsProfiles(profiles);
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(flag);
    }

}

效果图:

配置类:SwaggerConfig,设定发布(pro)环境启用swagger

package com.test.sprinbootswagger2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

// 标识配置类
@Configuration
// 开启swagger
@EnableSwagger2
public class SwaggerConfig {

    // 配置swagger的Docket实例
    @Bean
    public Docket docket(Environment environment){
        // 设置要显示的swagger环境
        Profiles profiles =Profiles.of("pro");
        // 通过environment.acceptsProfiles判断自己是否在设定的环境中
        boolean flag = environment.acceptsProfiles(profiles);
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(flag);
    }

}

效果图:

8081

 

小小解释一波。

1. 默认的application.properties,没有规定端口号。而dev规定端口是8080,pro规定端口号是8081

所以,默认application.properties选择哪个环境,等效于开启对应端口。开启的端口可以访问。关闭的端口,不能访问。

因此,8080能访问,8081拒绝。

2. 配置类里边选择的文件是否被启用。例子中,监听dev的配置文件,application.properties启用的是application-dev.properties。可以正常访问。当监听pro时,application.properties启用的还是application-dev.properties。即application-pro.properties没有被启用,所以不能访问swagger。

注意:可以设置多环境

Profiles profiles =Profiles.of("dev" , "pro");

 

配置:作者信息、分组、扫描位置、过滤扫描位置、是否启用。

 

package com.test.sprinbootswagger2.config;

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

import java.util.ArrayList;

@Configuration
// 开启swagger
@EnableSwagger2
public class SwaggerConfig {

    // 配置swagger的Docket实例
    @Bean
    public Docket docket1(){
        return new Docket(DocumentationType.SWAGGER_2)
                // 配置分组名称
                .groupName("A");
    }
    // 配置swagger的Docket实例
    @Bean
    public Docket docket2(){
        return new Docket(DocumentationType.SWAGGER_2)
                // 配置分组名称
                .groupName("B");
    }
    // 配置swagger的“我想做阿信”分组的Docket实例
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                // 配置分组名称
                .groupName("我想做阿信")
                /*
                配置是否启用swagger,默认true
                启用
                .enable(true)
                不启用
                .enable(false)
                */
                .select()
                /*
                可以不配置,不配置时,扫描全部。
                配置扫描包:
                必须在 .select()和 .build()之间配置

                一、配置扫描路径
                    1. 配置指定扫描的包——最常用
                    .apis(RequestHandlerSelectors.basePackage("com.test.sprinbootswagger2.controller"))
                    2. 扫描全部
                    .apis(RequestHandlerSelectors.any())
                    3. 都不扫描
                    .apis(RequestHandlerSelectors.none())
                    4. 扫描类上有XX注解的类(以@RestController注解为例)
                    .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                    5. 扫描方法上有XX注解的类(以@GetMapping注解为例)
                    .apis(RequestHandlerSelectors.withClassAnnotation(GetMapping.class))
                二、配置过滤路径,优先级比上边的高
                    1. 不扫描某路径
                    .paths(PathSelectors.ant("/test/**"))
                    2. 其他类似上边any、none、regex等
                */
                //
                .apis(RequestHandlerSelectors.basePackage("com.test.sprinbootswagger2.controller"))
                .build();
    }
    // 配置Swagger“我想做阿信”分组的信息=apiInfo
    private ApiInfo apiInfo() {
        Contact contact = new Contact("我想做阿信","https://blog.csdn.net/qq_42909053/","1273206268@qq.com");
        // 作者信息
        return new ApiInfo(
                "张仁杰的SwaggerAPI文档",
                "即使再小的船也能远航",
                "v1.0",
                "https://blog.csdn.net/qq_42909053/article/details/104982904",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<>()
        );
    }

}

运行测试:

配置:实体类

新建poji包:pojo

新建User实体类:User

代码:

package com.test.sprinbootswagger2.pojo;

public class User {

    public String username;
    public String password;
}

HelloController中添加User方法——关联实体类。接口中,返回值存在实体类,他就会被扫描到swagger中

 

package com.test.sprinbootswagger2.controller;

import com.test.sprinbootswagger2.pojo.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(String username){
        return "hello";
    }
    // 只要接口中,返回值存在实体类,他就会被扫描到swagger中
    @PostMapping("/user")
    public User user(){
        return new User();
    }
}

运行:

models里边有User,说明,实体类已经托管到swagger

添加注释

带注释的实体类:

package com.test.sprinbootswagger2.pojo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
// 实体类注释
@ApiModel("用户实体类")
public class User {
    // 参数注释
    @ApiModelProperty("用户名")
    public String username;
    @ApiModelProperty("密码")
    public String password;
}

带注释的接口:

package com.test.sprinbootswagger2.controller;

import com.test.sprinbootswagger2.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

// 类注释
@Api(tags = "hello控制类")
@RestController
public class HelloController {
    // 方法注释
    @ApiOperation("hello控制类")
    @RequestMapping("/hello")
    // @ApiParam形参注释
    public String hello(@ApiParam("用户名") String username){
        return "hello";
    }
    // 只要接口中,返回值存在实体类,他就会被扫描到swagger中
    @PostMapping("/user")
    public User user(){
        return new User();
    }
}

效果:

注意:加注释主要是给前端的人看的。

 

报错的解决

1. 弹框报错

问题产生原因:

1. 端口做了更改。但是访问时写错了端口。

按理说,端口更改了以后,原来的端口,没有开放,不应该会能访问的,但是不仅能访问还tm的ui报错。

原因,浏览器缓存的问题。

这个时候,如果清理下缓存,再访问,你会发现,无法访问!!

改一下访问接口就行了。

2. 在父子工程中,swagger的配置类SwaggerConfig写在其他模块。本类没有这个类。

在本类的启动类上添加:

@EnableSwagger2

新建项目之引入两个包,无法添加@Api、@ApiModel注解

未知原因,猜测可能是swagger的东西没有导入完全,也可能是IDEA加载的太慢。

我刷新了好几次。

然后还是用不了。

百度一波。

把自己导入的swagger注释了。用别人的。

<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-annotations</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-models</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <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>

然后可以用了。

为了去寻找问题的根源。

我把百度的代码注释,打开我的导包代码。

然后,tm的,@Api、@ApiModel注解竟然又能用了!!!

所以我怀疑是swagger没有加载完。

所以我又,新建个项目,测试一下。只导入自写的导包代码。

然后,tm的@Api、@ApiModel注解直接能用了。。。。

 

所以,现在,我也不知道到底怎么回事。

 

建议遇见相同问题的人。把IDEA关了再打开看看。

 

 
要在Spring Boot中集成Swagger,你需要做以下几个步骤: 1. 首先,确保你使用的是Spring Boot 2.5.x及之前的版本。因为从Spring Boot 2.6.x开始,Swagger已经从Spring Boot中移除了。 2. 在你的Spring Boot应用中添加Swagger的依赖。在pom.xml文件中,添加以下依赖: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` 3. 在启动类上添加`@EnableSwagger2`注解。这个注解会启用Swagger的功能。你可以将这个注解直接添加到你的Spring Boot启动类上,或者创建一个单独的配置类,在配置类中添加这个注解。 4. 配置Swagger的相关属性。你可以在`application.properties`或`application.yml`文件中添加以下配置: ```yaml springfox.documentation.swagger.v2.path=/swagger springfox.documentation.swagger.ui.enabled=true ``` 这些配置将指定Swagger的路径和UI的启用状态。 5. 编写API文档。在你的控制器类中,使用Swagger的注解来描述你的API接口。例如,你可以使用`@Api`注解来给你的控制器类添加一个API的描述,<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [SpringBoot教程(十六) | SpringBoot集成swagger(全网最全)](https://blog.csdn.net/lsqingfeng/article/details/123678701)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值