springcloud整合swagger2

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37279783/article/details/88416534

参考https://blog.csdn.net/ityqing/article/details/81217383的消息,2.2.2版本的与feign有冲突! 会报bean创建加载异常! 

pom.xml中加入Swagger2的依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.5.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.5.0</version>
</dependency>

在启动类同级目录下创建swagger2配置类

@Configuration
@EnableSwagger2
public class Swagger2 {

	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(meta())
				.select()
				.apis(RequestHandlerSelectors.basePackage("com.test"))//扫描的包路径
				.paths(PathSelectors.any())
				.build();
	}
	
	private ApiInfo meta() {
		return new ApiInfoBuilder()
				.title("我的API")
				.description("这是我的接口文档")
				.version("1.0.1")
				.build();
	}
}

在启动类加注解@EnableSwagger2,开启swagger2

@SpringBootApplication
@EnableSwagger2
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication .class, args);
    }

}

启动后访问http://localhost:8080/swagger-ui.html 

注意!!!如果遇到以下错误:

No mapping found for HTTP request with URI [/swagger-ui.html]

原因是Spring Boot自动配置本身不会自动把/swagger-ui.html这个路径映射到对应的目录META-INF/resources/下面,

需要增加配置文件,增加映射

如下:

@Configuration
public class WebMVCConfig extends WebMvcConfig {
    @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/");

    }

}

继续访问,正常! 

猜你喜欢

转载自blog.csdn.net/qq_37279783/article/details/88416534