- Swagger簡介。
Swagger2是一款restful接口文檔在線生成和在線調試工具。很多項目團隊利用Swagger自動生成接口文檔,保證接口文檔和代碼同步更新、在線調試。簡單地說,你可以利用這個工具生成你的接口文檔而不是自己去寫,而且生成的文檔在網站上可以讓別人調試。
- 開發環境
Eclipse+Maven+Swagger2
- 具體步驟
- 引入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)
