SpringBoot-swagger2 使用
1、引入依赖:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
2、ReqIntercept 请求拦截
package com.cn.dl.intercept;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
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;
/**
* 拦截所有请求
* Created by yanshao on 2019/4/30.
*/
@SpringBootConfiguration
public class ReqIntercept implements WebMvcConfigurer {
// @Override
// public void addInterceptors(InterceptorRegistry registry) {
// registry.addInterceptor(securityIntercept()).addPathPatterns("/**");
// }
//
// @Bean
// public SecurityIntercept securityIntercept() {
// return new SecurityIntercept();
// }
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.cn.dl"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("User 接口文档")
.description("User 接口文档 Swagger2 RESTful 风格的接口文档")
.termsOfServiceUrl("")
.version("2.0")
.build();
}
}
3、UserController
package com.cn.dl.controller;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
/**
* Created by yanshao on 2019/4/30.
*/
@RestController
@RequestMapping({"user"})
@Slf4j
public class UserController {
@PostMapping("query_user_info")
// @NeedLogin
public JSONObject queryUserInfo(@RequestParam("name") String name){
log.info("UserController 查询用户信息 name:{}",name);
JSONObject json = new JSONObject();
json.put("name",name);
json.put("age",25);
log.info("UserController 查询用户信息 result:{}",json.toJSONString());
return json;
}
@GetMapping("activity_info")
public JSONObject activityInfo(){
log.info("UserController 查询活动信息");
JSONObject json = new JSONObject();
json.put("date","2019-05-01");
json.put("topic","五一回家happy!");
log.info("UserController 查询活动信息 result:{}",json.toJSONString());
return json;
}
}
4、在启动类上加上注解:@EnableSwagger2
5、启动之后访问:http://localhost:8080/swagger-ui.html