一丶Maven配置
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
</dependency>
二丶Swagger配置
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Value("${spring.project.env}")
private String env;
@Bean
public Docket createBusinessApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).enable(checkEnv())
.groupName("业务相关接口")
.select()
.apis(RequestHandlerSelectors.basePackage("com.test.biz.affair.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("接口文档")
.description("restful接口")
.contact(new Contact("***、***", "https://google.com", ""))
.termsOfServiceUrl("")
.version("1.0")
.build();
}
/**
* 判断开发环境,只有预发和日常才开启swagger
*/
private boolean checkEnv() {
return Objects.equals(env, EnvEnum.PREPUB.getKey()) || Objects.equals(env, EnvEnum.DAILY.getKey());
}
}
@Configuration //引入静态资源
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 本地的静态文件
registry.addResourceHandler("/static/js/**")
.addResourceLocations("classpath:/static/js/");
// swagger
registry.addResourceHandler("/swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
// swagger的另一种ui界面
registry.addResourceHandler("/doc.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
需要注意,如果swagger的请求被内部拦截包装,需要去除包装,不然加载不了swagger的资源
三丶在Controller和pojo使用swagger的注解
@Api(tags = {"临时接口"}, hidden = true)
@RestController
@RequestMapping("/api/temp")
public class TempController {
@ApiOperation("测试")
@GetMapping("/test.json")
public void test() {
}
}
维护接口,使用注解来侵入到代码中,仁者见仁,个人还是比较接受这种方式,自己做接口测试也比较方便,比使用postman舒服