Spring Boot整合Swagger

Spring Boot整合Swagger


POM.xml

    
    
    
        io.springfox
        springfox-swagger2
        2.8.0
    
    
    
        io.springfox
        springfox-swagger-ui
        2.8.0
    

配置类

@Configuration
@EnableSwagger2
public class SpringfoxDocConfig {

    boolean test = true;
    @Bean
    public Docket customDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors
                        .basePackage("com.suoron.springboot.controller"))
                .paths(PathSelectors.any()).build()
                .useDefaultResponseMessages(false).enable(test);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("测试系统接口文档").build();
    }
}

使用

@Controller
@Api(value = "/test", tags = "测试接口")  //swagger分类标题注解
public class TestController {

    @RequestMapping(value = "/test",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "测试接口", notes = "自定义请求头sessionId,sessionId的值是登陆接口返回的")
    public String test(){
        return "Hello Springbootxxxx1111222333444!!!";
    }
}

Spring Boot全局异常

@ControllerAdvice  //不指定包默认加了@Controller和@RestController都能控制
public class MyControllerAdvice {

    /**
     * 全局异常处理,反正异常返回统一格式的map
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map exceptionHandler(Exception ex){
        Map map  = new HashMap();
        map.put("code",1001);
        map.put("mag",ex.getMessage());
        //发生异常进行日志记录,写入数据库或者其他处理,此处省略
        return map;
    }

}

你可能感兴趣的:(Spring Boot整合Swagger)