Mastering Spring Cloud
上QQ阅读APP看书,第一时间看更新

Using Swagger 2 together with Spring Boot

The integration between Spring Boot and Swagger 2 is realized by the Springfox project. It examines application at runtime to infer API semantics based on Spring configurations, class structure, and Java annotations. To use Swagger in conjunction with Spring, we need to add the following two dependencies to the Maven pom.xml and annotate the main application class with @EnableSwagger2:

<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>

The API documentation will be automatically generated from the source code by the Swagger library during application startup. The process is controlled by the Docket bean, which is also declared in the main class. A nice idea might be to get the API version from the Maven pom.xml file. We can get it by including the maven-model library in the classpath and using the MavenXpp3Reader class. We also set some other properties, such as title, author, and description using the apiInfo method. By default, Swagger generates documentation for all REST services, including those created by Spring Boot. We would like to limit this documentation only to our @RestController located inside the pl.piomin.services.boot.controller package:

  @Bean
public Docket api() throws IOException, XmlPullParserException {
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model = reader.read(new FileReader("pom.xml"));
ApiInfoBuilder builder = new ApiInfoBuilder()
.title("Person Service Api Documentation")
.description("Documentation automatically generated")
.version(model.getVersion())
.contact(new Contact("Piotr Mińkowski", "piotrminkowski.wordpress.com", "piotr.minkowski@gmail.com"));
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("pl.piomin.services.boot.controller"))
.paths(PathSelectors.any()).build()
.apiInfo(builder.build());
}