Boost Your Spring Boot API Docs: Switch from Swagger to Knife4j for Better UI

This article explains why Swagger can become cumbersome as API counts grow, introduces Knife4j as a powerful Swagger enhancement, and provides step‑by‑step instructions with code examples to integrate Knife4j into a Spring Boot project, highlighting its key features such as JSON folding, search, and global parameters.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Boost Your Spring Boot API Docs: Switch from Swagger to Knife4j for Better UI

When developing Spring Boot front‑back separation projects, Swagger is commonly used to generate, describe, debug, and visualize RESTful APIs, but as the number of interfaces grows its experience degrades: JSON parameters cannot be formatted, responses cannot be collapsed, and there is no search function.

1. About Knife4j

Knife4j, formerly swagger‑bootstrap‑ui, is an enhanced UI implementation for springfox‑swagger‑ui. It separates the UI from backend Java code, making it lightweight and more powerful. The original springfox‑swagger‑ui UI looks plain, while Knife4j provides a more elegant and feature‑rich interface.

After enhancement, swagger‑bootstrap‑ui looks like the image below, offering a more intuitive experience.

The improved Knife4j not only has a more elegant UI but also provides stronger functionality: the backend Java code and front‑end UI modules are separated, making it more flexible in micro‑service scenarios, and it offers dedicated enhancements for Swagger.

2. Integrating Swagger

First, add the official Swagger dependency to pom.xml:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

Then create a Java configuration class to set basic API information and the packages to scan:

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket docket() {
        Docket docket = new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .enable(true)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.codingmore.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("编程猫学习网站的 admin 管理端 API")
                .description("codingmore")
                .contact(new Contact("沉默王二&石磊", "https://tobebetterjavaer.com", "[email protected]"))
                .version("1.0")
                .build();
    }
}

Access the Swagger UI at http://localhost:9002/swagger-ui/ (append swagger-ui to the project path).

In a controller, common Swagger annotations such as @Api and @ApiOperation are used to describe resources and operations.

@Controller
@Api(tags = "文章 ")
@RequestMapping("/posts")
public class PostsController {
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("删除")
    public ResultObject<String> delete(@RequestParam long postsId) {
        return ResultObject.success(postsService.removePostsById(postsId) ? "删除成功" : "删除失败");
    }
}

@Api marks a controller class as a Swagger resource; only classes with this annotation are scanned.

@ApiOperation describes a specific method.

Swagger also supports other annotations like @ApiParam and @ApiResponses, which are omitted here for brevity.

3. Integrating Knife4j

Knife4j follows the same usage pattern as Swagger, allowing a seamless switch.

Step 1: Add the Knife4j starter dependency (no need to include springfox-boot-starter).

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <!-- Search Maven Central for the latest 3.x version -->
    <version>3.0.2</version>
</dependency>

Step 2: Enable the enhanced features by adding @EnableOpenApi to a configuration class.

@Configuration
@EnableOpenApi
public class SwaggerConfig {}

Step 3: Restart the Spring Boot application and visit the documentation at http://localhost:9002/doc.html.

If the project uses Spring Security, add a whitelist for Knife4j URLs in application.yml:

secure:
  ignored:
    urls:
      - /doc.html
      - /swagger-ui/**
      - /swagger/**
      - /swagger-resources/**
      - /**/v3/api-docs

4. Knife4j Features

1) Login authentication support – the "Authorize" button lets you add a token that will be sent with subsequent requests.

2) JSON folding – unlike Swagger, Knife4j can collapse large JSON responses.

3) Offline documentation – export API docs as Markdown, HTML, or Word files.

4) Global parameters – define header or query parameters that are automatically added to every request.

5) API search – a search box in the top‑right corner lets you find APIs by address, name, or description.

5. Conclusion

Beyond the features mentioned above, Knife4j offers many other practical enhancements that can significantly improve development efficiency. Switching from Swagger to Knife4j only requires two steps: replace the springfox-boot-starter dependency with knife4j-spring-boot-starter, and change the documentation URL from http://${host}:${port}/swagger-ui.html to http://${host}:${port}/doc.html, remembering to whitelist the URLs if security is enabled.

https://doc.xiaominfo.com/knife4j/documentation/enhance.html
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpring BootAPI documentationSwaggerKnife4j
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.