一、添加依赖
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
二、添加配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
@Configuration
public class Swagger2 {
@Bean
public Docket createRestApi() {
// .apis(RequestHandlerSelectors.basePackage("需要添加到 API 接口文档的接口包路径"))
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.xxl.sso.server.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API 接口文档")
.description("简单优雅的restfun风格,http://blog.csdn.net/saytime")
.termsOfServiceUrl("http://blog.csdn.net/saytime")
.version("1.0")
.build();
}
}
三、启动类添加注解
@EnableSwagger2
五、补充
1、如果访问四中网址出现 404 错误,则添加配置类 WebMvcConfig
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/templates/**")
.addResourceLocations("classpath:/META-INF/resources/templates/");
}
}
2、相关注解
- @Api(value = "控制器名称 ",description = "控制器说明"),加在控制器类上面
- @ApiOperation(value="接口名称", notes="接口说明") ,加在控制器接口方法上面
- @ApiIgnore 忽略该控制器类或者接口方法,类和方法上面都可以加