java集成swagger

本文详细介绍如何在Java项目中集成Swagger,包括引入依赖、编写启动类、配置参数等关键步骤,适用于Spring MVC框架。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文写一下java集成swagger的主要步骤(留作记录)

1、引入swagger所需的jar包(版本可用2.6.1)

        <!--swagger本身不支持spring mvc的,springfox把swagger包装了一下,让他可以支持springmvc-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.4.0</version>
        </dependency>

2、编写swagger启动类SwaggerConfig.java

package com.xxx;


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.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2
@Configuration
public class DemoSwaggerConfig {
    @Bean
    public Docket petApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(true)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.hnac"))
                .paths(PathSelectors.any())
                .build();

    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("xxx演示平台API").description("").termsOfServiceUrl("http://localhost:8080/xxx-demo").version("1.0").build();
    }

}

进阶配置

package xxx.xxx;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.google.common.base.Predicates;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
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.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;

@Configuration
@EnableSwagger2
@EnableKnife4j
@ConditionalOnProperty(prefix = "swaggerConfig", name = "switchFlag", havingValue = "true")
public class SwaggerConfig implements WebMvcConfigurer {
    @Bean
    public Docket createRestApi() {
        ParameterBuilder parameterBuilder = new ParameterBuilder();
        List<Parameter> parameters = new ArrayList<>();
        parameterBuilder.name("Authorization") // Updates the parameter name
                .description("JSON Web Token")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false)
                .build();
        parameters.add(parameterBuilder.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(Predicates.or(RequestHandlerSelectors.basePackage("com.hnac.xxx"),RequestHandlerSelectors.basePackage("org.springframework.security.oauth2")))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("xxxAPI文档")
                        .description("包含xxxxxxxx等")
                        .version("1.0")
                        .build()).globalOperationParameters(parameters);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
    }
}

更详细的可以看看此文章:java集成Swagger的详细步骤_Mr_庄的博客-优快云博客_java swagger

### Java项目中集成Swagger和Knife4j 在Java项目中,特别是基于Spring Boot的应用程序,可以通过引入Swagger和其增强版本Knife4j来实现API文档的自动生成与管理。这不仅提高了开发效率,还增强了API的可读性和易用性。 #### 添加依赖项 对于Maven构建工具,在`pom.xml`文件内加入如下依赖: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> <!-- Knife4j扩展 --> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>3.0.3</version> </dependency> ``` 这些依赖会自动配置好Swagger UI以及提供更美观友好的前端展示效果[^1]。 #### 配置Swagger 创建一个名为`SwaggerConfig.java`的新类用于初始化Swagger设置: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configuration public class SwaggerConfig { @Bean(value = "defaultApi2") public Docket defaultApi2() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(new ApiInfoBuilder() .title("API Documentation") // 文档标题 .description("Description of APIs") // 描述 .contact(new Contact("Name", "", "")) .license("") .licenseUrl("") .version("1.0") .build()) .select() /* 定义扫描包路径 */ .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } } ``` 这段代码定义了一个Docket Bean实例并设置了基本的信息如标题、描述等,并指定了要被解析成API接口的方法所在的包位置。 #### 启动应用后的访问地址 完成上述步骤后启动应用程序,默认情况下可以在浏览器输入以下URL查看生成的API文档页面: - **Swagger UI**: `http://localhost:8080/swagger-ui/index.html` - **Knife4j Enhanced UI**: `http://localhost:8080/doc.html` 这两个链接分别指向原始版和美化过的UI界面,其中后者提供了更多实用功能比如在线调试请求参数等功能。 通过这种方式能够快速有效地为现有的RESTful服务添加详细的交互式文档支持,极大地简化了前后端协作流程中的沟通成本。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌晨两点钟同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值