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

springboot项目利用Swagger2生成在线接口文档

2019-01-10 17:37 513 查看
  • Swagger简介。

         Swagger2是一款restful接口文档在线生成和在线调试工具。很多项目团队利用Swagger自动生成接口文档,保证接口文档和代码同步更新、在线调试。简单地说,你可以利用这个工具生成你的接口文档而不是自己去写,而且生成的文档在网站上可以让别人调试。

  • 开发环境

     Eclipse+Maven+Swagger2

  •   具体步骤
  1.      引入Maven依赖。(很多JAVA组件使用的第一步)

     我的maven坐标如下

       

<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.7,当然也可以引用其他版本的。

  2.  添加JAVA配置类。用于配置Swagger运行信息。JAVA配置类本质上和SSM项目的XML配置一样,但是比较安全(这一点还有待研究)

package XXX.springboot.config;

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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("XXX.springboot.web"))
.paths(PathSelectors.any())
.build();
}

private ApiInfo apiInfo(){
return new ApiInfoBuilder().title("Spring Boot中使用Swagger生成Restful-Api文档")
.version("1.0").build();
}

}

 这里说明一下:

ApiInfoBuilder().title("Spring Boot中使用Swagger构建Rest Api")   title里面的内容是生成接口文档页面的标题。
RequestHandlerSelectors.basePackage("XXX.springboot.web")     括号里面的内容是你的Contrller接口所在包的路径。
(为什么这么配??我也不知道.问JAVA大神,他回答:这么配就对了!为什么,框架自动反射(其实他也不知道)!)


3. 最后一步,添加接口注释
@Api(value="/test", tags="产品接口模块")
@RestController
public class CategoryController {

@Autowired CategoryService categoryService;

@ApiOperation(value="展示产品信息", notes = "展示产品信息")
@RequestMapping("/listCategory")
public List<Category> listCategory(Model m) throws Exception {
List<Category> cs=categoryService.listAllCategory();

m.addAttribute("cs", cs);

return cs;
}
}

这里用到了两个注解:

@Api用于类,表示标识这个类是swagger资源。

@ApiOperation用于方法,表示这是一个http请求操作。

swagger还有很多注解,比如@ApiParam,@ApiModel。我还没来得及一一了解。

 

4.运行springboot程序,在浏览器中访问

我创建的springboot程序就是一个简单的JAVA程序。所以在Eclipse中直接运行就好了。

在浏览器中输入:http://127.0.0.1:8888/swagger-ui.html 进行访问.                    (127.0.0.1是回环地址,我的springboot项目的tomcat服务器端口配置了为8888)

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: