赞
踩
spring boot 版本:2.6.4
swagger 版本:2.0.7
<!-- 引入swagger -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.7</version>
</dependency>
@Configuration @EnableSwagger2WebMvc public class Knife4jConfiguration { @Bean(value = "defaultApi2") public Docket defaultApi2() { Docket docket=new Docket(DocumentationType.SWAGGER_2) .apiInfo(new ApiInfoBuilder() //.title("swagger-bootstrap-ui-demo RESTful APIs") .description("# swagger-bootstrap-ui-demo RESTful APIs") .termsOfServiceUrl("http://www.xx.com/") .contact("xx@qq.com") .version("1.0") .build()) //分组名称 .groupName("2.X版本") .select() //这里指定Controller扫描包路径 .apis(RequestHandlerSelectors.basePackage("com.github.xiaoymin.knife4j.controller")) .paths(PathSelectors.any()) .build(); return docket; } }
官网并没有指明要指定静态文件地址 直接访问可能会报404错误
@SpringBootApplication
public class DemoApplication implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 解决swagger无法访问
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
// 解决swagger的js文件无法访问
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
@Api(tags = "用户增删改查") @RestController @RequestMapping("userController") public class UserController { /** * 使用线程安全的map存储user */ static Map<Long, User> userMap= Collections.synchronizedMap(new HashMap<Long, User>()); /** * 获取用户列表 * @return */ @ApiOperation(value = "用户列表") @GetMapping("/getUser") public List<User> getUserList(){ return new ArrayList<>(userMap.values()); } /** * 用户添加 * @return */ @ApiImplicitParam(dataTypeClass=User.class,required = true) @ApiOperation(value = "用户添加") @PostMapping("/addUser") public Object addUser(@RequestBody User user){ userMap.put(user.getUserId().longValue(),user); return "用户添加成功"; } /** * 用户修改 * @return */ @ApiOperation(value = "用户修改") @PutMapping("/updateUser") public Object updateUser(@RequestBody User user){ User entity = userMap.get(user.getUserId().longValue()); entity.setAge(user.getAge()); entity.setUserName(user.getUserName()); userMap.put(user.getUserId().longValue(),entity); return "更新成功"; } /** * 删除用户 * @return */ @ApiOperation(value = "删除用户") @DeleteMapping("/deleteUser") public Object deleteUser(Long userId){ userMap.remove(userId); return "删除成功"; } } // 实体类 @Data public class User { /** * 用户id */ private Integer userId; /** *用户姓名 */ private String userName; /** * 用户年龄 */ private Integer age; }
server:
port: 8081
// 如果启动报这个错误
Failed to start bean ‘documentationPluginsBootstrapper‘
那么在配置文件中添加
# 配置路径匹配策略
spring:
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER
启动报错原因可访问:处理documentationPluginsBootstrapper报错
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。