5

jersey と gradle を使用したスプリング ブート アプリケーションがあり、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'
    }
    
  • ばねのブーツの塗布:

    @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に移動すると、basic-error-controller のみがリストされた「緑色」の UI 画面が表示されます。私自身のコントローラーはありません。

私は何を間違えましたか?みんなありがとう

4

3 に答える 3

11

バージョンの時点で、2.5.0 springfoxは spring-mvc コントローラーのみをサポートしています。jersey のような Jax-rs 実装はサポートされていません。

springfox を使用するための現在の代替手段は、jax-rs/jersey ベースのサービスに swagger- coreライブラリを使用することです。

でジャージのサポートを実装するために必要なフックがあります2.6+これは、この問題でそれを実装する方法の抜粋です

現在、ResourceConfig には「getClasses」と呼ばれるメソッドがあり、登録されているすべてのものを一覧表示します。リソース、フィルターなどのように...多分これが役立つかもしれません。ただし、返されるクラスは、フィルターまたは jersey2 に登録できるその他のものである可能性があることに注意してください。

于 2016-06-24T01:25:52.307 に答える
7

Springfox swagger UI から Jersey メソッドを表示できるようにするには:

  1. https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-2.X-Project-Setup-1.5に従って、Jersey で Swagger を構成します。
  2. http://springfox.github.io/springfox/docs/current/に従って Springfox Swagger を構成します。
  3. SpringBoot アプリケーション構成クラスを追加します (@Configuration で注釈を付けます):

    @Value("${springfox.documentation.swagger.v2.path}") private String swagger2Endpoint;

  4. application.properties で、Jersey swagger.json への参照を追加します。

    springfox.documentation.swagger.v2.path=/{change it to your Jersey api path}/swagger.json

これで、Jersey Swagger によって生成された API が Springfox Swagger UI ページから表示されるはずです。

于 2017-02-14T13:57:17.663 に答える
3

springfox の更新については @Dilip-Krishnan に、質問については @Guy-Hudara に感謝します。Springboot ジャージを使用したアプリでスワッガーをサポートするために、次のソリューションを思いつきました。

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:
 * http://stackoverflow.com/questions/37640863/springfox-swagger-no-api-docs-with-spring-boot-jersey-and-gardle
 * 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);

    }
}

それは私にとってうまくいきました

于 2016-08-09T09:47:11.840 に答える