这是一个swagger接口文档页面,至于swagger有什么好处我就不说了,网上一大堆,现在我记录一下怎么在springboot中配置swagger。
1.添加依赖,网上也有很多依赖的版本,现在我这个是比较新也比较主流的版本。
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
2.添加一个Swagger2的配置类,随你怎么命名Swagger2Config/Swagger2都可以。需要注意的是类上面添加两个注解和@bean注解
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//为controller包路径
.apis(RequestHandlerSelectors.basePackage("org.common.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("使用Swagger2构建RESTful APIs")
.description("admin swagger测试页面")
.termsOfServiceUrl("")
.contact("千山暮雪")
.version("1.0")
.build();
}
}
其实这个格式和内容都是固定的,可以直接复制,但需要注意的是controller包的路径,一定要注意,千万别错了,我就是在这错了,偏偏自己还没有注意到。以前习惯的是com.xxx.xxx.controller,自己不相信踩了坑……
然后其他的对应的分别是这些内容
3.添加WebMvcConfig配置类,或者是在已有的该配置中添加
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
}
直接复制即可,功能:在未登录的情况下通过在springboot的security安全机制的过滤器。
4.最后就是添加一个测试的controller
code:
@Api(description = "swagger测试接口")
@RestController
@RequestMapping("/demoController")
public class SwaggerDemoController {
@ApiOperation(value = "s1" , notes="s2")
@RequestMapping
@GetMapping("/getTest")
public String getTest(Integer i) {
System.out.println("开始调用接口");
return new Json("返回数据").toString()+ i;
}
}
这就ok了,下一篇讲讲遇到的小问题,出现的小bug怎么解决。