欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot集成springdoc-openapi的案例講解(模擬前端請求)

 更新時間:2025年06月21日 10:52:57   作者:一百減一是零  
文章介紹了Spring?Boot集成Swagger時版本沖突的常見問題,推薦使用springdoc-openapi-ui替代Springfox,因其配置更簡單且遵循OpenAPI規(guī)范,同時提供驗證和界面優(yōu)化方法,對springboot集成springdoc-openapi相關知識感興趣的朋友一起看看吧

描述---痛點

我們項目中很多時候都會用到swagger swagger2 (以下全部稱swagger)
當我們配置Springboot集成swagger時,要選對應的版本才可以,不然就會報各種錯誤,版本不匹配,或高或低
例如
Application run failed

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

java.lang.IllegalStateException: Cannot set parent bean factory to self

等等。就會很麻煩

或者是當我們?nèi)ド塻pring-boot的時候  也會遇到這些問題,這時我們可以嘗試更改用springdoc-openapi-ui取替代swagger

springdoc-openapi-ui中間已經(jīng)包含了swagger也就是說,使用springdoc-openapi-ui是可以替代的。他的配置相對的話就比較簡單

配置起來也不會很麻煩,我們看下是如何配置

Springfox對比springdoc-openapi

在該片中我用的是springdoc-openapi,相對來說更加適合于我,簡單輕量,配置更少一些,還有一點就是直接更喜歡

Springfox和springdoc-openapi都是用于在Spring Boot應用程序中集成OpenAPI和Swagger UI的庫。

1. 成熟度和維護性:

- Springfox是一個相對成熟和廣泛使用的庫,已經(jīng)存在一段時間,并且有一個活躍的社區(qū)進行維護和更新。

- springdoc-openapi是相對較新的庫,但也在不斷發(fā)展和更新,它的目標是提供更簡單、更輕量級的集成方式。

2. 依賴和配置:

- Springfox通常需要引入`springfox-boot-starter`等相關依賴,并進行一些配置,以便生成和展示Swagger文檔。

- springdoc-openapi通常只需要引入`springdoc-openapi-ui`依賴,并且不需要太多的配置即可生成和展示OpenAPI文檔。

3. 注解和使用方式:

- Springfox使用`@Api`、`@ApiOperation`等注解來定義API文檔,并提供了一些配置選項來自定義文檔生成。

- springdoc-openapi使用`@io.swagger.v3.oas.annotations`包下的注解來定義API文檔,它遵循OpenAPI規(guī)范,并提供了一些額外的注解來進行更細粒度的控制。

4. 特性和擴展性:

- Springfox提供了一些額外的特性和擴展,如支持Spring Security集成、自定義UI主題等。

- springdoc-openapi也提供了一些特性和擴展,如支持Spring Security集成、自定義UI主題等,但可能相對較少。

如何選擇使用Springfox還是springdoc-openapi

如果你需要更成熟、功能更豐富的庫,并且對配置和注解的靈活性有更高的要求,那么Springfox可能是一個不錯的選擇。

如果你更傾向于簡單、輕量級的集成方式,并且遵循OpenAPI規(guī)范的優(yōu)先級更高,那么springdoc-openapi可能更適合你。

應用目錄結(jié)構(gòu)

pom文件

我用的springboot是2.7.10還是比較新的。

只需要引入springdoc-openapi-ui這一個即可

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.10</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
<!--Springfox/swagger遷移springdoc-openapi & springdoc-openapi最新版本和springboot應用集成-->
        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-ui</artifactId>
            <version>1.5.12</version>
        </dependency>
<!-- 可以不引入 -->
        <dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>0.9.12</version>
        </dependency>

修改時間 2025年4月15日13:20:24 BEGIN

springboot3.2.5版本配置

<dependency>
			<groupId>org.reflections</groupId>
			<artifactId>reflections</artifactId>
			<version>${reflections.version}</version>
			<exclusions>
				<exclusion>
					<artifactId>javassist</artifactId>
					<groupId>org.javassist</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springdoc</groupId>
			<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
			<version>2.3.0</version>
		</dependency>
		<dependency>
			<groupId>com.github.xiaoymin</groupId>
			<artifactId>knife4j-openapi3-spring-boot-starter</artifactId>
			<version>4.4.0</version>
			<exclusions>
				<exclusion>
					<groupId>org.webjars</groupId>
					<artifactId>swagger-ui</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<!--添加Knife4j依賴-->
		<dependency>
			<groupId>com.github.xiaoymin</groupId>
			<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
			<version>4.5.0</version>
		</dependency>
不需要yml中添加配置,添加一個properties即可
knife4j.enable=true
knife4j.base-package=cn.axa.provider
knife4j.exclude-path=/error
knife4j.setting.path=/provider/doc.html
knife4j.setting.title=API??
knife4j.setting.description=API??
knife4j.setting.version=1.0.0
knife4j.setting.license.name=Apache 2.0

修改時間 2025年4月15日13:20:36  END

新增測試controller

`@Tag`注解用于指定相關測試controller的API

StaffController

package com.yun.greedy.modules.staff.controller;
import com.yun.greedy.modules.staff.entity.Staff;
import com.yun.greedy.modules.staff.service.StaffService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ex_yangqiusheng
 * @since 2023-06-29
 */
@Slf4j
@RestController
@Tag(name = "StaffController測試數(shù)據(jù)", description = "測試數(shù)據(jù)驗證")
@RequestMapping("/staff")
public class StaffController {
    @Autowired
    private StaffService staffService;
    @GetMapping("/list")
    public List<Staff> list() {
        List<Staff> list = staffService.getBaseMapper().selectList(null);
        log.info("結(jié)果值打印--------------------");
        list.forEach(System.out::println);
        return list;
    }
}

YUserController

package com.yun.greedy.modules.yuser.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yun.greedy.modules.yuser.entity.YUser;
import com.yun.greedy.modules.yuser.service.YUserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Tag(name = "YUserController賬戶操作", description = "賬戶相關信息")
@RequestMapping("/YUser")
@RestController
public class YUserController {
    @Autowired
    private YUserService yUserService;
    @GetMapping(value = "/queryYUserById")
    public YUser queryYUserId(Long yId){
        YUser yUser = yUserService.getById(yId);
        return yUser;
    }
    @GetMapping(value = "/queryYUserByName")
    public List<YUser> queryYUserName(String name){
        List<YUser> list = yUserService.getBaseMapper().selectList(new QueryWrapper<YUser>().eq("y_name", name));
        return list;
    }
    @GetMapping(value = "/searchYUser")
    public YUser searchYUser(Long yId,String yName){
        YUser yUser = YUser.builder().yId(yId).yName(yName).build();
        return yUser;
    }
    @PostMapping(value = "/postYUser")
    public YUser queryYUser(@RequestBody JSONObject jsonObject) throws JSONException {
        long yId = jsonObject.getLong("yId");
        String yName = jsonObject.getString("yName");
        YUser yUser = YUser.builder().yId(yId).yName(yName).build();
        return yUser;
    }
}

啟動測試看下

啟動完成,如果不知道如何搭建新項目的,可以借鑒看下這篇文章,從零到一新建項目

http://www.dbjr.com.cn/program/343957cn3.htm

驗證swagger

http://localhost:8088/swagger-ui/index.html

瀏覽器輸入這個地址,顯示這個頁面說明swagger正常。

yml中添加配置

springdoc:
  api-docs:
    #是否開啟文檔功能,默認為true,可不配置
    enabled: true
  swagger-ui:
    # 訪問ip:host/api,可直接訪問Swagger springdoc
    path: /api

配置OpenApiConfig 

package com.yun.greedy.config;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.tags.Tag;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ConfigurationBuilder;
import org.springdoc.core.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import java.util.Set;
/**
 * 這里的@OpenAPIDefinition 和@SecurityScheme都是springdoc注解,主要聲明API信息:標題、版本、許可證、安全性、服務器、標簽、安全性和拓展文檔信息。
 * 配置jwt時,@SecurityScheme(type = SecuritySchemeType.HTTP, name = “JWT”, scheme = “bearer”, in = SecuritySchemeIn.HEADER).scheme 還支持basic。
 * 具體可查看官網(wǎng)文檔: https://springdoc.org/index.html
 */
@OpenAPIDefinition(security = @SecurityRequirement(name = "Authorization"))
@SecurityScheme(type = SecuritySchemeType.APIKEY, name = "Authorization", scheme = "Authorization", in = SecuritySchemeIn.HEADER)
@Configuration
public class OpenApiConfig {
    private String title = "寒舞";//標題
    private String group = "group";//分組名稱
    private String description = "被你捧做神明的人,怎會低頭看塵埃里的你";//簡介
    private String version = "ver_1.0.0";//版本
    private String termsOfService = "https://blog.csdn.net/weixin_59383491";//服務Url
    private String contactName = "一百減一是零";//作者
    @Bean
    public OpenAPI springOpenAPI() {
        return new OpenAPI()
                .info(getInfo());
    }
    public Info getInfo() {
        return new Info()
                .title(title)
                .description(description)
                .version(version)
                .termsOfService(termsOfService)
                .license(buildLicense())
                .contact(buildContact());
    }
    public Contact buildContact() {
        return new Contact()
                .name(contactName)
                .email("517306474@qq.com")//Your API Contact Email
                .url("https://blog.csdn.net/weixin_59383491");//Your API Contact URL
    }
    public License buildLicense() {
        return new License()
                .name("APACHE LICENSE, VERSION 2.0")//許可證
                .url("https://www.apache.org/licenses/LICENSE-2.0.html");
    }
    @Bean
    public GroupedOpenApi publicApi() {
        return GroupedOpenApi.builder()
                .group(group)
                .pathsToMatch("/YUser/**","/staff/**")//API路徑,不是類路徑
                //這里是添加對應標簽
                /*.addOpenApiCustomiser(openApi -> {
                    Tag staffTag = new Tag();
                    staffTag.setName("myController");//標簽名稱
                    staffTag.setDescription("驗證一下所有Controller");//描述
                    // 指定某個包中的所有controller
                    String packagePath = "com.yun.greedy.modules.staff.controller";
                    Set<Class<?>> controllerClasses = getControllerClasses(packagePath);
                    for (Class<?> controllerClass : controllerClasses) {
                        String controllerName = controllerClass.getSimpleName();
                        staffTag.addExtension("x-controller-" + controllerName, controllerClass.getName());
                    }
                    // 指定單獨的controller
//                    String controllerName = "YourControllerName";
//                    Class<?> controllerClass = getControllerClass(packagePath, controllerName);
//                    if (controllerClass != null) {
//                        staffTag.addExtension("x-controller-" + controllerName, controllerClass.getName());
//                    }
                    if (null != openApi.getTags()){
                        openApi.getTags().add(staffTag);
                    } else {
                        openApi.addTagsItem(staffTag);//添加標簽
                    }
                })*/
                .build();
    }
    //顯式地配置掃描器
    private Reflections reflectionsConf(String packagePath){
        return new Reflections(new ConfigurationBuilder()
                .forPackages(packagePath)
                .addScanners(new SubTypesScanner()));
    }
    // 獲取某個包中的所有controller類
    private Set<Class<?>> getControllerClasses(String packagePath) {
        Reflections reflections = reflectionsConf(packagePath);
        return reflections.getTypesAnnotatedWith(RestController.class);
    }
    // 獲取單獨的controller類
    private Class<?> getControllerClass(String packagePath, String controllerName) {
        Reflections reflections = reflectionsConf(packagePath);
        Set<Class<?>> controllerClasses = reflections.getTypesAnnotatedWith(RestController.class);
        for (Class<?> controllerClass : controllerClasses) {
            if (controllerClass.getSimpleName().equals(controllerName)) {
                return controllerClass;
            }
        }
        return null;
    }
}

驗證配置swagger

http://localhost:8088/api

重啟應用,輸入此地址,展示以下頁面顯示配置成功!

驗證接口

無參

try一下

執(zhí)行結(jié)果

有參

執(zhí)行結(jié)果

現(xiàn)在看起來是沒有問題的,配置,展示,執(zhí)行結(jié)果都是正常,但是這個頁面看著削為有點簡陋

優(yōu)化下界面openapi

添加jar包

<!--美化swagger-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-springdoc-ui</artifactId>
            <version>3.0.3</version>
        </dependency>

  http://localhost:8088/doc.html

重啟應用,輸入地址,展示以下界面就可以了。

 驗證結(jié)果

OK執(zhí)行成功,到此就算是完成了

到此這篇關于springboot集成springdoc-openapi(模擬前端請求)的文章就介紹到這了,更多相關springboot集成springdoc-openapi內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Spring Boot四大神器之CLI的具體使用

    Spring Boot四大神器之CLI的具體使用

    本文主要介紹了Spring Boot四大神器之CLI的具體使用,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-10-10
  • spring中@Reference注入為空的解決方法

    spring中@Reference注入為空的解決方法

    今天上線遇到了問題,所以抽空記錄一下,本文主要介紹了spring中@Reference注入為空的解決方法,需要的朋友們下面隨著小編來一起學習學習吧
    2021-06-06
  • Centos中安裝jdk案例講解

    Centos中安裝jdk案例講解

    這篇文章主要介紹了Centos中安裝jdk案例講解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • Java面試??贾瓹oncurrentHashMap多線程擴容機制詳解

    Java面試??贾瓹oncurrentHashMap多線程擴容機制詳解

    幾乎所有的后端技術面試官都要在?ConcurrentHashMap?技術的使用和原理方面對小伙伴們進行刁難,本文主要來和大家聊聊ConcurrentHashMap多線程的擴容機制,希望對大家有所幫助
    2023-05-05
  • idea項目debug模式啟動,斷點失效,斷點紅點內(nèi)無對勾問題及解決

    idea項目debug模式啟動,斷點失效,斷點紅點內(nèi)無對勾問題及解決

    這篇文章主要介紹了idea項目debug模式啟動,斷點失效,斷點紅點內(nèi)無對勾問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • Java自定義實現(xiàn)鏈隊列詳解

    Java自定義實現(xiàn)鏈隊列詳解

    這篇文章主要為大家詳細介紹了Java自定義實現(xiàn)鏈隊列的相關資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • Java加解密工具類源碼示例

    Java加解密工具類源碼示例

    最近在項目中接觸到了數(shù)據(jù)加解密的業(yè)務,數(shù)據(jù)加密技術是網(wǎng)絡中最基本的安全技術,這篇文章主要給大家介紹了關于Java加解密工具類源碼的相關資料,需要的朋友可以參考下
    2023-11-11
  • Java實現(xiàn)二叉樹的建立、計算高度與遞歸輸出操作示例

    Java實現(xiàn)二叉樹的建立、計算高度與遞歸輸出操作示例

    這篇文章主要介紹了Java實現(xiàn)二叉樹的建立、計算高度與遞歸輸出操作,結(jié)合實例形式分析了Java二叉樹的創(chuàng)建、遍歷、計算等相關算法實現(xiàn)技巧,需要的朋友可以參考下
    2019-03-03
  • RocketMQ?Push?消費模型示例詳解

    RocketMQ?Push?消費模型示例詳解

    這篇文章主要為大家介紹了RocketMQ?Push?消費模型示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-09-09
  • Java map 優(yōu)雅的元素遍歷方式說明

    Java map 優(yōu)雅的元素遍歷方式說明

    這篇文章主要介紹了Java map 優(yōu)雅的元素遍歷方式說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-10-10

最新評論