SpringFox Swagger 3.0.0 适配SpringMvc、SpringWebflux

头像
码农笔录
2020-08-25 后端 阅读量 3234

现在后台基本都用到了swagger,无论开发人员调试测试,还是前端用,都很方便,前段时间如果用SpringWebflux的话,只能用3.0快照版,不过最近已经发布了正式版,时隔2年多,新版本还是有很大的变化。

https://github.com/springfox/springfox

NOTE: Would love feedback to make this better

  • Remove explicit dependencies on springfox-swagger2

  • Remove any @EnableSwagger2… annotations

  • Add the springfox-boot-starter dependency

  • Springfox 3.x removes dependencies on guava and other 3rd party libraries (not zero dep yet! depends on spring plugin and open api libraries for annotations and models) so if you used guava predicates/functions those will need to transition to java 8 function interfaces.

  • 移除了2.x版本的冲突版本,移除了guava等

  • 移除了@EnableSwagger2

  • 新增了springfox-boot-starter

1.添加依赖

是的你没看错,直接提供了springboot的start

gradle

compile group: 'io.springfox', name: 'springfox-boot-starter', version: '3.0.0'

maven

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>

然后应用主类增加注解@EnableOpenApi,删除之前版本的SwaggerConfig.java,启动项目,访问地址:http://localhost:8200/swagger-ui/index.html,注意2.x版本中访问的地址的为http://localhost:8200/swagger-ui.html  

2.配置资源目录

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport { //这个和swagger没有关系,是配置跨域的 @Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST","DELETE","OPTIONS")
.allowCredentials(false).maxAge(3600);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.
addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
.resourceChain(false);
super.addResourceHandlers(registry);
}

@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/swagger-ui/")
.setViewName("forward:/swagger-ui/index.html");
}
}

默认是这样的,不影响你使用


默认是以上界面,当然之前的配置还可以继续配置,只不过是可选配置,那我们继续加上

@Configuration
public class SwaggerConfiguration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.aiprose.mbp.controller"))
// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}

private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot mybatis plus框架demo")
.description("springboot mybatis plus框架demo")
.contact(new Contact("nelson", "https://www.aiprose.com/", "mail_yanpeng@163.com"))
.version("1.0")
.build();
}
}