5分钟 springboot 整合swagger2

springboot 整合swagger2

1.maven配置文件中添加依赖

<properties>
    <swagger2.version>2.2.2</swagger2.version>
</properties>
--------------------------------------------------
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>${swagger2.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>${swagger2.version}</version>
</dependency>

2.添加SwaggerConfig.java 文件

@Configuration
@EnableSwagger2
public class SwaggerConfig {
	@Value("${server.context-path}")
	private String pathMapping;

	@Bean
	public Docket createRestApi() {
		System.out.println("https://localhost:8443" + pathMapping + "/swagger-ui.html");
		return new Docket(DocumentationType.SWAGGER_2)
				.groupName("test")
				.genericModelSubstitutes(ResponseEntity.class)
				.useDefaultResponseMessages(true)
				.forCodeGeneration(false)
				.pathMapping(pathMapping)
				.select()
				.apis(RequestHandlerSelectors.basePackage("com.weapp.controller"))
				.paths(PathSelectors.any())
				.build()
				.apiInfo(apiInfo());
	}
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("标题")
				.description("描述")
				.termsOfServiceUrl("服务条款网址")
				.contact("justubborn")
				.version("1.0")
				.build();
	}

3.配置静态资源映射WebMvcConfig.java

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}

4.在接口中使用swagger注解(参考官方文档)

@RestController
@RequestMapping
public class AppUserController {

	@Api(name=ApiConstant.GET_USER)
	@RequestMapping(value = "/api/v1/user/{id}", method = RequestMethod.GET, produces = "application/json")
	public Map<String, String> get(@PathVariable String id){
		ImmutableMap<String, String> map = ImmutableMap.of("id", id);
		return map;
	}
}

5.访问https://localhost:8443/weapp/swagger-ui.html

posted @ 2018-05-17 23:08  Justubborn  阅读(164)  评论(0编辑  收藏  举报