1.引入依赖的jar包(这里面有坑,exclusion默认,引入1.5.21,不然ApiImplicitParam dataType="long" 报错,亲历 )
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.21</version>
</dependency>
<!--swagger-ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2.application.properties 新增 spring.swagger2.enabled=true
3.增加 SwaggerConfig 配置文件,内容如下:
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
@Value(value = "${spring.swagger2.enabled}")
private Boolean swaggerEnabled;
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(swaggerEnabled)
.select()
.apis(RequestHandlerSelectors.basePackage("com.xinnet.knowledgecms.web"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("接口文档")
.description("新知接口文档")
.termsOfServiceUrl("http://xxxx.com:8065/")
.version("1.0")
.build();
}
}
4.配置注解
@Api(description = "测试接口")
@Controller
public class IndexController {
@ApiOperation("添加用户")
@AllowAccess
@GetMapping("/addUser")
@ApiImplicitParams({
@ApiImplicitParam(name="id",value="用户id",dataType="long", paramType = "query",defaultValue ="1000"),
@ApiImplicitParam(name="name",value="用户名",dataType="string", paramType = "query",defaultValue="zhangsan")
})
public String test(HttpServletRequest request,long id ,String name) {
return "index1.html";
}
5。访问 swagger
http://xxxx/swagger-ui.html