解決springboot集成swagger碰到的坑(報404)

一:項目使用springboot集成swagger進行調試

配置swagger非常簡單,主要有三步:

1、添加swagger依賴

<!-- 引入 swagger等相關依賴 -->
<dependency>
 <groupId>io.springfox</groupId>
 <artifactId>springfox-swagger2</artifactId>
 <version>2.6.1</version>
</dependency>
<dependency>
 <groupId>io.springfox</groupId>
 <artifactId>springfox-swagger-ui</artifactId>
 <version>2.6.1</version>
</dependency>

2、進行swagger的配置

package com.sailing.springbootmybatis.config;
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;
 
/**
 * @author baibing
 * @project: springboot-mybatis
 * @package: com.sailing.springbootmybatis.config
 * @Description: swagger2配置類
 * @date 2018/9/25 15:35
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sailing.springbootmybatis.controller"))
                .paths(PathSelectors.any())
                .build();
    }
 
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("SPRING-BOOT整合MYBATIS--API說明文檔")
                .description("2018-8完成版本")
                .contact("Sailing西安研發中心-baibing")
                .version("1.0")
                .license("署名-非商用-相同方式共享 4.0轉載請保留原文鏈接及作者")
                .licenseUrl("https://creativecommons.org/licenses/by-nc-sa/4.0/")
                .build();
    }
}

3、在controller層添加相應的註解(@Api 和 @ApiOperation 以及 @ApiIgnore 等)

package com.sailing.springbootmybatis.controller;
import com.sailing.springbootmybatis.bean.Userinfo;
import com.sailing.springbootmybatis.common.log.LogOperationEnum;
import com.sailing.springbootmybatis.common.log.annotation.MyLog;
import com.sailing.springbootmybatis.common.response.BuildResponseUtil;
import com.sailing.springbootmybatis.common.response.ResponseData;
import com.sailing.springbootmybatis.common.websocket.WebSocketServer;
import com.sailing.springbootmybatis.service.RedisService;
import com.sailing.springbootmybatis.service.UserinfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
 
/**
 * @author baibing
 * @project: springboot-mybatis
 * @package: com.sailing.springbootmybatis.controller
 * @Description: Userinfo controller 控制層
 * @date 2018/9/12 10:07
 */
@RestController
@Api(value = "USERINFO", description = "用戶信息測試controller")
public class UserinfoController{
    @Autowired
    private UserinfoService userinfoService;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private RedisService redisService;
    /**
     * 查找指定id對應的用戶
     * @param id
     * @return
     */
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    @MyLog(type = LogOperationEnum.SELECT,value = "查詢指定id的用戶信息")
    @ApiOperation(value = "查詢指定id的用戶信息接口", notes = "查詢指定id的用戶信息接口")
    public ResponseData getUser(@PathVariable(value = "id") Integer id){
        return userinfoService.findById(id);
    }
    /**
     * 查找所有用戶
     * @return
     */
    @RequestMapping(value = "/users", method = RequestMethod.GET)
    @MyLog(type = LogOperationEnum.SELECT,value = "查詢全部用戶信息")
    @ApiOperation(value = "查詢所有用戶信息接口", notes = "查詢所有用戶信息接口")
    public ResponseData getAllUsers(){
        return userinfoService.findAllUsers();
    }
 
    /**
     * 查找所有用戶(帶分頁)
     * @param page 當前頁數
     * @param rows 每頁顯示條數
     * @return
     */
    @RequestMapping(value = "/users/p", method = RequestMethod.GET)
    @ApiOperation(value = "查詢所有用戶信息接口(帶分頁)", notes = "查詢所有用戶信息接口(帶分頁)")
    public ResponseData getAllUsers(Integer page, Integer rows){
        return userinfoService.findAllUsers(page, rows);
    }
 
    /**
     * 新增用戶 (帶參數校驗@Valid)
     * 註意:BindingResult 對象必須在 @Valid 的緊挨著的後面,否則接收不到錯誤信息
     * @Valid 可以校驗json 也可以校驗表單傳遞的對象屬性
     * @param userinfo
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.POST)
    @MyLog(type = LogOperationEnum.INSERT, value = "新增用戶信息")
    @ApiOperation(value = "新增用戶接口(包含參數校驗)", notes = "新增用戶接口(包含參數校驗)")
    public ResponseData saveUserinfo(@RequestBody @Valid Userinfo userinfo, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return BuildResponseUtil.buildFailResponse(bindingResult.getFieldError().getDefaultMessage());
        }
        return userinfoService.saveUser(userinfo);
    }
 
    /**
     * 刪除指定用戶
     * @param id 用戶id
     * @return
     */
    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    @ApiOperation(value = "刪除指定id的用戶信息接口", notes = "刪除指定id的用戶信息接口")
    public ResponseData deleteUser(@PathVariable Integer id){
        return userinfoService.deleteUser(id);
    }
 
    /**
     * 更新用戶
     * @param userinfo
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.PUT)
    @ApiOperation(value = "更新指定id用戶信息接口", notes = "更新指定id用戶信息接口")
    public ResponseData updateUserinfo(@RequestBody Userinfo userinfo){
        return userinfoService.updateUser(userinfo);
    }
 
    /**
     * 給指定用戶推送消息
     * @param userName 用戶名
     * @param message 消息
     * @throws IOException
     */
    @RequestMapping(value = "/socket", method = RequestMethod.GET)
    @ApiIgnore //使用此註解忽略方法的暴露,也可以用在controller上
    @ApiOperation(value = "給指定用戶推送socket消息接口", notes = "給指定用戶推送socket消息接口")
    public void testSocket(@RequestParam String userName,@RequestParam String message){
        webSocketServer.sendInfo(userName, message);
    }
 
    /**
     * 測試redis接口保存String類型action
     * @param address
     * @return
     */
    @RequestMapping(value = "/redis", method = RequestMethod.POST)
    @ApiIgnore //使用此註解忽略方法的暴露,也可以用在controller上
    @ApiOperation(value = "redis中添加String數據接口", notes = "redis中添加String數據接口")
    public ResponseData setString(@RequestBody String address){
        System.out.println(address);
        return redisService.setValue(address);
    }
 
    /**
     * 測試redis接口保存實體類型action
     * @param userinfo
     * @return
     */
    @RequestMapping(value = "/redis/userinfo", method = RequestMethod.POST)
    @ApiIgnore //使用此註解忽略方法的暴露,也可以用在controller上
    @ApiOperation(value = "redis中添加Userinfo實體接口", notes = "redis中添加Userinfo實體接口")
    public ResponseData setEntity(@RequestBody Userinfo userinfo){
        return redisService.setEntityValue(userinfo);
    }
    /**
     * 測試redis接口讀取實體類型action
     * @param key
     * @return
     */
    @RequestMapping(value = "/redis/userinfo/{key}", method = RequestMethod.GET)
    @ApiIgnore //使用此註解忽略方法的暴露,也可以用在controller上
    @ApiOperation(value = "redis中讀取指定key對應的數據接口", notes = "redis中讀取指定key對應的數據接口")
    public ResponseData getEntity(@PathVariable String key){
        return redisService.getEntityValue(key);
    }
 
    /**
     *
     * @param list
     * @return
     */
    @RequestMapping(value = "/redis/userList", method = RequestMethod.POST)
    @ApiIgnore //使用此註解忽略方法的暴露,也可以用在controller上
    @ApiOperation(value = "redis中添加包含Userinfo實體的集合接口", notes = "redis中添加包含Userinfo實體的集合接口")
    public ResponseData setCollection(@RequestBody List<Userinfo> list){
        return redisService.setCollectionValue(list);
    }
 
    /**
     * 測試redis接口讀取實體類型action
     * @param key
     * @return
     */
    @RequestMapping(value = "/redis/userList/{key}", method = RequestMethod.GET)
    @ApiOperation(value = "redis中讀取指定key對應的集合數據接口", notes = "redis中讀取指定key對應的集合數據接口")
    public ResponseData getCollection(@PathVariable String key){
        return redisService.getCollectionValue(key);
    }
}

二:到這裡配置就結束瞭

訪問 http://127.0.0.1:端口/項目路徑/swagger-ui.html 就ok瞭, 頁面如下:

swagger-ui界面展示

三:項目運行瞭一段時間後訪問上面連接突然報 404 錯誤

百思不得其解,但是可以肯定的是加瞭什麼配置導致,最後在application.yml 中發現瞭一個配置:

spring.mvv.resources.add-mapping:false

將其註釋掉熟悉的界面又回來瞭,查閱資料發現這個配置是不自動給靜態資源添加路徑,導致swagger-ui.html找不到資源,知道原因後摸索看能不能在保留以上配置的前提下自己手動給swagger-ui.html添加靜態資源路徑呢?

package com.sailing.springbootmybatis.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 
/**
 * 在SpringBoot2.0及Spring 5.0 WebMvcConfigurerAdapter已被廢棄,目前找到解決方案就有
 * 1 直接實現WebMvcConfigurer (官方推薦)
 * 2 直接繼承WebMvcConfigurationSupport
 * @ https://blog.csdn.net/lenkvin/article/details/79482205
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @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/");
    }
}

發現通過以上代碼手動給swagger-ui.html指定路徑也可以解決404的問題。

Springboot集成Swagger遇到無限死循環

解決方法

1.萬能辦法,重啟,我自己用好使

2.同事說的方法,因重啟無效,斷網一會

3.修改端口號,目前一直用的

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: