以下將介紹如何在Spring Boot上使用Springfox Swagger2.0
IDE: Eclipse Neon Release (4.6.0)
Plugin: STS
1.新增專案
2.勾選所需功能模組(Web)
下一步
建立專案中
產生的專案目錄結構
3.加入相依jar檔
Maven
|
<dependency>
<groupId> io.springfox</groupId >
<artifactId> springfox-swagger2 </artifactId>
<version> 2.5.0</version >
</dependency>
|
Gradle
|
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.5.0'
|
4.建立Swagger配置
org.itri.config.Swagger2SpringBoot.java
|
@SpringBootApplication
@EnableSwagger2
@ComponentScan ("org.iwlp.controller")
public class Swagger2SpringBoot {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Swagger2SpringBoot. class, args);
}
@Bean
public Docket newsApi() {
return new Docket(DocumentationType. SWAGGER_2)
.apiInfo(apiInfo())
.select()
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title( "Spring REST Sample with Swagger" )
.description( "Spring REST Sample with Swagger" )
.version( "2.0")
.build();
}
}
|
5.建立Controller
org.iwlp.controller.TestController
|
@RestController
@RequestMapping (value = "/api")
public class TestController {
private static final Logger log = LoggerFactory.getLogger(TestController. class);
@RequestMapping(method=RequestMethod. GET,value="/hello" )
public @ResponseBody Object sayHello(
@RequestParam(required = false, value = "message") String message
) {
log.debug("{}", "message");
return "Controller HELLO:" + message;
}
}
|
6.如何使用SwaggerUI
這時啟動Spring Boot
API DOC:http://127.0.0.1:8080/v2/api-docs
可以看到REST API都使用JSON所描述
並可用呼叫此REST API:http://127.0.0.1:8080/api/hello?message=hi
找個SwaggerUI把API DOC網址貼上即可看到專案底下所有REST API
若是本機的SwaggerUI如何呈現
先去Swagger官方網站下載UI
重啟Spring Boot後,再用瀏覽器進入SwaggerUI
SwaggerUI : http://127.0.0.1:8080/apis/index.html
7.如何修改REST API的描述、預設值?
org.iwlp.controller.TestController
|
@RestController
@RequestMapping (value = "/api")
public class TestController {
private static final Logger log = LoggerFactory.getLogger(TestController. class);
@RequestMapping(method=RequestMethod. GET,value="/hello" )
@ApiImplicitParams({
@ApiImplicitParam(name = "message" , value = "輸入文字訊息", required = true, defaultValue = "Hi,Swagger" ,dataType = "string", paramType = "query")
})
public @ResponseBody Object sayHello(
@RequestParam(value = "message" ) String message
) {
log.debug("{}" , "message");
return "Controller HELLO:" + message;
}
}
|
8.下載專案
參考資料:
Springfox Reference Documentation
Usage of Swagger 2.0 in Spring Boot Applications to document APIs
沒有留言:
張貼留言