Spring Boot整合Swagger
POM.xml
<!-- swagger2 -->
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
配置类
@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<String,Object> exceptionHandler(Exception ex){
Map<String,Object> map = new HashMap<String,Object>();
map.put("code",1001);
map.put("mag",ex.getMessage());
//发生异常进行日志记录,写入数据库或者其他处理,此处省略
return map;
}
}
网友评论