您的位置:首页 > 编程语言 > Java开发

在springboot中使用Swagger自动化生成restapi接口文档

2017-06-27 00:00 387 查看
首先,在pom.xml文件中,加入引用包:

<!-- https://mvnrepository.com/artifact/io.swagger/swagger-annotations -->
<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>

然后在工程中,创建Swagger配置文件。注意,在配置文件中,指定Swagger扫描的包:

package com.my.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.my.controller")) // 对controller下所有api进行监控
.paths(PathSelectors.any()) // 对所有路径进行监控
.build();
}

}

最后,在启动程序中,将根目录指向Swagger自动生成的API展示页面/swagger-ui.html:

package com.my;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Controller
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@RequestMapping("/")
String home() {
return "redirect:/swagger-ui.html";
}
}

重启应用,就能够看到API接口文档:



最后,需要注意的是,在controller文件中,所有方法必须指定方法名,否则Swagger会自动生成get、post、delete、options、header、put、trace 共7种方法的接口文档,即便没有使用:

@RequestMapping(value="/getUserInfo",method=RequestMethod.GET)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  springboot Swagger