Springfox swagger - 没有 api-docs with spring boot jersey 和 gradle
Springfox swagger - no api-docs with spring boot jersey and gradle
我有一个带有 jersey 和 gradle 的 spring 启动应用程序,我正在尝试使用 springfox 自动生成 API 文档。
我已按照此处的步骤操作:http://springfox.github.io/springfox/docs/current/
这是我所做的:
build.gradle:
dependencies {
.........
//Swagger
compile "io.springfox:springfox-swagger2:2.4.0"
compile "io.springfox:springfox-bean-validators:2.4.0"
compile 'io.springfox:springfox-swagger-ui:2.4.0'
}
Spring 引导应用程序:
@SpringBootApplication
@EnableSwagger2
public class AnalyzerServiceApplication{
public static void main(String[] args) {
SpringApplication.run(AnalyzerServiceApplication.class, args);
}
@Bean
public Docket analyzerApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.pathMapping("/")
.directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(
newRule(typeResolver.resolve(DeferredResult.class,
typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
typeResolver.resolve(WildcardType.class)))
.useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.GET,
newArrayList(new ResponseMessageBuilder()
.code(500)
.message("500 message")
.responseModel(new ModelRef("Error"))
.build()))
.securitySchemes(newArrayList(apiKey()))
.securityContexts(newArrayList(securityContext()))
.enableUrlTemplating(true)
.globalOperationParameters(
newArrayList(new ParameterBuilder()
.name("someGlobalParameter")
.description("Description of someGlobalParameter")
.modelRef(new ModelRef("string"))
.parameterType("query")
.required(true)
.build()))
.tags(new Tag("Pet Service", "All apis relating to pets"))
;
}
@Autowired
private TypeResolver typeResolver;
private ApiKey apiKey() {
return new ApiKey("mykey", "api_key", "header");
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("/anyPath.*"))
.build();
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope
= new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return newArrayList(
new SecurityReference("mykey", authorizationScopes));
}
@Bean
SecurityConfiguration security() {
return new SecurityConfiguration(
"test-app-client-id",
"test-app-client-secret",
"test-app-realm",
"test-app",
"apiKey",
ApiKeyVehicle.HEADER,
"api_key",
"," /*scope separator*/);
}
@Bean
UiConfiguration uiConfig() {
return new UiConfiguration("validatorUrl");
}
现在是控制器(球衣)
@Api(value = "/widget")
@Path("/widget")
@Component
public class WidgetController extends BaseController {
@Autowired
private WidgetService widgetService;
@GET
@Path("/secHealth")
@ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class)
@ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied"),
@ApiResponse(code = 404, message = "Pet not found") })
public Response getPet() {
//Do something
}
当我启动服务器并导航至 http://localhost:8080/swagger-ui.html 时,我可以看到 "green" UI 屏幕,其中仅列出了基本错误控制器。我自己的控制器不在那里。
我做错了什么?
谢谢
盖伊
从版本 2.5.0
开始 springfox 仅支持 spring-mvc 控制器。不支持像球衣这样的 Jax-rs 实现。
当前使用 springfox 的替代方法是将 swagger-core 库用于基于 jax-rs/jersey 的服务。
它确实具有在 2.6+
中实现球衣支持所需的挂钩。这是在 this issue
中实现它的方法的摘录
Currently ResourceConfig has a method called "getClasses" which will
list everything registerted. like Resources, Filters,etc... Maybe this
could help. But be aware that the returning classes could also be
filters or any other stuff you could register with jersey2.
感谢@Dilip-Krishnan 的 springfox 更新和@Guy-Hudara 的问题,我想出了以下解决方案来在我的 springboot jersey 驱动的应用程序中获得 swagger 支持:
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
/**
* As of version 2.5.0 springfox only supports spring-mvc controllers. Jax-rs implementations like jersey aren't supported.
*
* Fortunately io.swagger::swagger-jersey2-jaxrs::1.5.3 have the hooks needed to implement support for jersey in 2.6+.
*
* some pointers I used to get this swagger config done and swagger-core, springboot and jersey integrated:
*
* https://www.insaneprogramming.be/blog/2015/09/04/spring-jaxrs/
* https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-2.X-Project-Setup-1.5#adding-the-dependencies-to-your-application
*
*/
@Configuration
public class SwaggerConfiguration {
@Autowired
ResourceConfig resourceConfig;
@PostConstruct
public void configure() {
resourceConfig.register(ApiListingResource.class);
resourceConfig.register(SwaggerSerializers.class);
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion("1.0.2");
beanConfig.setSchemes(new String[]{"http"});
beanConfig.setHost("localhost:8888");
beanConfig.setBasePath("/api");
beanConfig.setResourcePackage("com.my.resource");
beanConfig.setPrettyPrint(true);
beanConfig.setScan(true);
}
}
这对我来说效果很好
能够从 Springfox swagger 中看到 Jersey 方法 UI:
- 按照 https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-2.X-Project-Setup-1.5
使用 Jersey 配置你的 Swagger
- 按照http://springfox.github.io/springfox/docs/current/
配置Springfox Swagger
添加你的SpringBoot应用配置class(用@Configuration注解):
@Value("${springfox.documentation.swagger.v2.path}")
private String swagger2Endpoint;
在 application.properties 添加对你的球衣的引用 swagger.json:
springfox.documentation.swagger.v2.path=/{change it to your Jersey api path}/swagger.json
现在您应该能够看到从 Springfox Swagger UI 页面生成 api 的 Jersey Swagger。
我有一个带有 jersey 和 gradle 的 spring 启动应用程序,我正在尝试使用 springfox 自动生成 API 文档。
我已按照此处的步骤操作:http://springfox.github.io/springfox/docs/current/
这是我所做的:
build.gradle:
dependencies { ......... //Swagger compile "io.springfox:springfox-swagger2:2.4.0" compile "io.springfox:springfox-bean-validators:2.4.0" compile 'io.springfox:springfox-swagger-ui:2.4.0' }
Spring 引导应用程序:
@SpringBootApplication @EnableSwagger2 public class AnalyzerServiceApplication{ public static void main(String[] args) { SpringApplication.run(AnalyzerServiceApplication.class, args); } @Bean public Docket analyzerApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .pathMapping("/") .directModelSubstitute(LocalDate.class, String.class) .genericModelSubstitutes(ResponseEntity.class) .alternateTypeRules( newRule(typeResolver.resolve(DeferredResult.class, typeResolver.resolve(ResponseEntity.class, WildcardType.class)), typeResolver.resolve(WildcardType.class))) .useDefaultResponseMessages(false) .globalResponseMessage(RequestMethod.GET, newArrayList(new ResponseMessageBuilder() .code(500) .message("500 message") .responseModel(new ModelRef("Error")) .build())) .securitySchemes(newArrayList(apiKey())) .securityContexts(newArrayList(securityContext())) .enableUrlTemplating(true) .globalOperationParameters( newArrayList(new ParameterBuilder() .name("someGlobalParameter") .description("Description of someGlobalParameter") .modelRef(new ModelRef("string")) .parameterType("query") .required(true) .build())) .tags(new Tag("Pet Service", "All apis relating to pets")) ; } @Autowired private TypeResolver typeResolver; private ApiKey apiKey() { return new ApiKey("mykey", "api_key", "header"); } private SecurityContext securityContext() { return SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex("/anyPath.*")) .build(); } List<SecurityReference> defaultAuth() { AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; return newArrayList( new SecurityReference("mykey", authorizationScopes)); } @Bean SecurityConfiguration security() { return new SecurityConfiguration( "test-app-client-id", "test-app-client-secret", "test-app-realm", "test-app", "apiKey", ApiKeyVehicle.HEADER, "api_key", "," /*scope separator*/); } @Bean UiConfiguration uiConfig() { return new UiConfiguration("validatorUrl"); }
现在是控制器(球衣)
@Api(value = "/widget") @Path("/widget") @Component public class WidgetController extends BaseController { @Autowired private WidgetService widgetService; @GET @Path("/secHealth") @ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Pet not found") }) public Response getPet() { //Do something }
当我启动服务器并导航至 http://localhost:8080/swagger-ui.html 时,我可以看到 "green" UI 屏幕,其中仅列出了基本错误控制器。我自己的控制器不在那里。
我做错了什么? 谢谢 盖伊
从版本 2.5.0
开始 springfox 仅支持 spring-mvc 控制器。不支持像球衣这样的 Jax-rs 实现。
当前使用 springfox 的替代方法是将 swagger-core 库用于基于 jax-rs/jersey 的服务。
它确实具有在 2.6+
中实现球衣支持所需的挂钩。这是在 this issue
Currently ResourceConfig has a method called "getClasses" which will list everything registerted. like Resources, Filters,etc... Maybe this could help. But be aware that the returning classes could also be filters or any other stuff you could register with jersey2.
感谢@Dilip-Krishnan 的 springfox 更新和@Guy-Hudara 的问题,我想出了以下解决方案来在我的 springboot jersey 驱动的应用程序中获得 swagger 支持:
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
/**
* As of version 2.5.0 springfox only supports spring-mvc controllers. Jax-rs implementations like jersey aren't supported.
*
* Fortunately io.swagger::swagger-jersey2-jaxrs::1.5.3 have the hooks needed to implement support for jersey in 2.6+.
*
* some pointers I used to get this swagger config done and swagger-core, springboot and jersey integrated:
*
* https://www.insaneprogramming.be/blog/2015/09/04/spring-jaxrs/
* https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-2.X-Project-Setup-1.5#adding-the-dependencies-to-your-application
*
*/
@Configuration
public class SwaggerConfiguration {
@Autowired
ResourceConfig resourceConfig;
@PostConstruct
public void configure() {
resourceConfig.register(ApiListingResource.class);
resourceConfig.register(SwaggerSerializers.class);
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion("1.0.2");
beanConfig.setSchemes(new String[]{"http"});
beanConfig.setHost("localhost:8888");
beanConfig.setBasePath("/api");
beanConfig.setResourcePackage("com.my.resource");
beanConfig.setPrettyPrint(true);
beanConfig.setScan(true);
}
}
这对我来说效果很好
能够从 Springfox swagger 中看到 Jersey 方法 UI:
- 按照 https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-2.X-Project-Setup-1.5 使用 Jersey 配置你的 Swagger
- 按照http://springfox.github.io/springfox/docs/current/ 配置Springfox Swagger
添加你的SpringBoot应用配置class(用@Configuration注解):
@Value("${springfox.documentation.swagger.v2.path}") private String swagger2Endpoint;
在 application.properties 添加对你的球衣的引用 swagger.json:
springfox.documentation.swagger.v2.path=/{change it to your Jersey api path}/swagger.json
现在您应该能够看到从 Springfox Swagger UI 页面生成 api 的 Jersey Swagger。