一.步骤总结
1.在pom.xml中添加依赖
2.在主类中添加注解:@EnableSwagger2
3.通过浏览器访问:
4.自定义注解设置不需要生成接口文档的方法
二.步骤代码示例
1.在pom.xml中添加依赖
在项目的pom.xml中导入Spring-fox依赖。目前最新版本为2.9.2,所以导入的依赖也是这个版本。其中springfox-swagger2是核心内容的封装。springfox-swagger-ui是对swagger-ui的封装。
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2.在主类中添加注解:@EnableSwagger2
添加此注解后表示对当前项目中全部控制器进行扫描
@SpringBootApplication
@EnableSwagger2
@MapperScan(basePackages = "com.yrp.mapper")
public class JspApplication {
public static void main(String[] args) {
SpringApplication.run(JspApplication.class, args);
}
}
3.通过浏览器访问:
启动项目后在浏览器中输入http://ip:port/swagger-ui.html即可以访问到swagger-ui页面,在页面中可以可视化的进行操作项目中所有接口。
4.自定义注解设置不需要生成接口文档的方法
自定义贴在方法上的注解,并在SwaggerConfig中配置,在不需要生成接口文档的方法上面添加@NotIncludeSwagger注解后,该方法将不会被Swagger进行生成在接口文档中。
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotlncludeSwagger {
}
@Configuration
public class SwaggerConfig {
@Bean
public Docket getDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(swaggerDemoApiInfo())
.select()
.apis(not(withMethodAnnotation(NotlncludeSwagger.class)))
.build();
}
//配置ApiInfo信息
private ApiInfo swaggerDemoApiInfo() {
return new ApiInfoBuilder()
.contact(new Contact("yrp", "http://www.baidu.com", "xxx163.com"))
.title("这里是swageer标题")
.description("这里是swagger的描述")
.version("1.0.0")
.build();
}
}