1、在pom.xml中导入坐标

  <!--knife4j-->
  <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-spring-boot-starter</artifactId>
        <version>3.0.2</version>
  </dependency>

2、在Controller中测试数据(此处的controller是mybatisplus自动生成)

@ApiOperation("用户接口")
@Controller
@RequestMapping("/swaggerdemo/user")
public class UserController {

    @ApiOperation("用户登录")
    @GetMapping("/login")
    public String login(){
        return "login";
    }
}

ps:ApiOperation表示菜单的提示信息

3、启动时发现没有找到/doc.html

No mapping for GET /doc.html

在启动类上加上此注解即可解决

@EnableKnife4j

4、启动一下项目,发现报错

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

这时候只需要在application.yml中添加mvc的配置即可

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

访问localhost:8080/doc.html即可在线测试接口

5、测试接口时,发现报错

{
  "timestamp": "2023-02-25T04:35:47.152+00:00",
  "status": 500,
  "error": "Internal Server Error",
  "path": "/redisdemo/user/login"
}

只需要将MybatisPlus自动生成的注解@Controller和@RequestMapping换成@RestController即可

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐