Swagger 2 with Spring MVC and Spring Boot

Sample to config Swagger 2 with Spring MVC 4 and Spring Boot 2

Add Swagger 2 for Spring MVC

  • Spring MVC version: 4.2.7
  • Swagger version: 2.7.0

Add swagger2 dependency into pom.xml.

If using fastjson, must use the version greater then 1.2.15, as not support swagger 2 json below that version. Use jackson is safe.

Add Spring configuration.

Then we need create Swagger config class.

And then add it into bean context.

If the api-docs too big, swagger ui will have problem to render, so need to use path grouping to split the documents

1
2
3
4
5
6
7
8
9
10
11
12
13
14
	@Bean
	public Docket businessDocket() {
		return new Docket(DocumentationType.SWAGGER_2)
				.groupName("business") //group name
				.select()
				.paths(businessPaths()) //path selecotr, PathSelectors.any() means everything
				.build()
				.apiInfo(apiInfo());
	}
	@SuppressWarnings("unchecked")
	private Predicate<String> businessPaths() {
		return or(PathSelectors.regex("/business.*"));//regex from google guava
	}

Add Swagger 2 for Spring Boot

  • Spring Boot version: 2.0.3
  • Swagger version: 2.8.0

Similar with Spring MVC, we need add dependency libararies and config the swagger

Add swagger2 dependency into pom.xml.

1
2
3
4
5
6
7
8
9
10
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>${springfoxSwagger2Version}</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>${springfoxSwagger2Version}</version>
		</dependency>

Then we need create Swagger config class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Configuration
@EnableSwagger2
public class Swagger2Config {

	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
				.apis(RequestHandlerSelectors.basePackage("com.durain.bootu.controller")).paths(PathSelectors.any()).build();
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder().title("Bootu API Document")
				.description("Rest API Document")
				.termsOfServiceUrl("http://abc.123.com").version("1.0").build();
	}
}

Verify the result

After success start the service, and you can verity the resuts via http://localhost:8080/v2/api-docs, or use the swagger ui http://localhost:8080/swagger-ui.html