7

Using Springfox to document jax-rs services in a Spring app を解決した後、SpringFox の JSON 応答に API が表示されないことがわかりました。

{
  "swagger": "2.0",
  "info": {
    "description": "Some description",
    "version": "1.0",
    "title": "My awesome API",
    "contact": {
      "name": "my-email@domain.org"
    },
    "license": {}
  },
  "host": "localhost:9090",
  "basePath": "/myapp"
}

springfox-servlet.xml は次のとおりです。

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean class="com.wordnik.swagger.jaxrs.listing.ApiListingResourceJSON" />
    <bean class="com.wordnik.swagger.jaxrs.listing.ApiDeclarationProvider" />
    <bean class="com.wordnik.swagger.jaxrs.listing.ResourceListingProvider" />
</beans>

これはプロパティ ファイルにあります。

swagger.resourcePackage=org.myapp

Swagger は、リフレクティブ jax-rs スキャナーを使用して実装クラスを見つけるように構成されています。

@Component
public class SwaggerConfiguration {

    @Value("${swagger.resourcePackage}")
    private String resourcePackage;

    @PostConstruct
    public void init() {
        ReflectiveJaxrsScanner scanner = new ReflectiveJaxrsScanner();
        scanner.setResourcePackage(resourcePackage);
        ScannerFactory.setScanner(scanner);

        ClassReaders.setReader(new DefaultJaxrsApiReader());

        SwaggerConfig config = ConfigFactory.config();
        config.setApiVersion(apiVersion);
        config.setBasePath(basePath);
    }

    public String getResourcePackage() {
        return resourcePackage;
    }

    public void setResourcePackage(String resourcePackage) {
        this.resourcePackage = resourcePackage;
    }
}

ドキュメントの構成は次のとおりです。

@Configuration
@EnableSwagger2
public class ApiDocumentationConfiguration {
    @Bean
    public Docket documentation() {
        System.out.println("=========================================== Initializing Swagger");
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/")
                .apiInfo(metadata());
    }

    @Bean
    public UiConfiguration uiConfig() {
        return UiConfiguration.DEFAULT;
    }

    private ApiInfo metadata() {
        return new ApiInfoBuilder()
                .title("My awesome API")
                .description("Some description")
                .version("1.0")
                .contact("my-email@domain.org")
                .build();
    }
}

API アノテーションを使用したサンプル クラスを次に示します。

@Api(value = "activity")
@Service
@Path("api/activity")
@Produces({ MediaType.APPLICATION_JSON })
public class ActivityService {

    @Autowired
    private CommandExecutor commandExecutor;
    @Autowired
    private FetchActivityCommand fetchActivityCommand;

    @ApiOperation(value = "Fetch logged-in user's activity", httpMethod = "GET", response = Response.class)
    @GET
    @Path("/mine")
    @Consumes(MediaType.TEXT_PLAIN)
    @Produces(MediaType.APPLICATION_JSON)
    @Authorization(rejectionMessage = Properties.Authorization.NOT_LOGGED_IN_MESSAGE_PREFIX + "view your activities.")
    public List<Activity> listMyActivities(@Context HttpServletResponse response, @Context HttpServletRequest request) throws IOException {
        return buildActivityList(response, (UUID) request.getSession().getAttribute(Properties.Session.SESSION_KEY_USER_GUID));
    }
    ...
}

API を公開しないのはなぜですか? wordnik swagger ライブラリを使用すると、これを解決できますか、または解決策が改善されますか?

4

2 に答える 2

21

デフォルトでは、SpringFox は Spring MVC を使用して実装された REST サービスを文書化します -@EnableSwagger2アノテーションを追加するのと同じくらい簡単です

@SpringBootApplication
@EnableSwagger2
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

SpringFox を JAX-RS で動作させることができました。最初に、SpringFox とともにいくつかの Swagger 依存関係を追加しました。

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-jersey")
    compile("io.springfox:springfox-swagger-ui:2.4.0")
    compile("io.springfox:springfox-swagger2:2.4.0")
    compile("io.swagger:swagger-jersey2-jaxrs:1.5.8")
    testCompile("junit:junit")
}

次に、Spring Boot アプリケーションで Swagger を使用して JAX-RS (Jersey) を有効にしました。

@Component
@ApplicationPath("/api")
public static class JerseyConfig extends ResourceConfig {

    public JerseyConfig() {

        BeanConfig swaggerConfig = new BeanConfig();
        swaggerConfig.setBasePath("/api");
        SwaggerConfigLocator.getInstance().putConfig(SwaggerContextService.CONFIG_ID_DEFAULT, swaggerConfig);

        packages(getClass().getPackage().getName(), ApiListingResource.class.getPackage().getName());
    }

}

すべての JAX-RS エンドポイントがコンテキストの下にあることに注意してください。/apiそうしないと、Spring-MVC ディスパッチャーと競合します。

最後に、Jersey エンドポイント用に生成された swagger json を Springfox に追加する必要があります。

@Component
@Primary
public static class CombinedSwaggerResourcesProvider implements SwaggerResourcesProvider {

    @Resource
    private InMemorySwaggerResourcesProvider inMemorySwaggerResourcesProvider;

    @Override
    public List<SwaggerResource> get() {

        SwaggerResource jerseySwaggerResource = new SwaggerResource();
        jerseySwaggerResource.setLocation("/api/swagger.json");
        jerseySwaggerResource.setSwaggerVersion("2.0");
        jerseySwaggerResource.setName("Jersey");

        return Stream.concat(Stream.of(jerseySwaggerResource), inMemorySwaggerResourcesProvider.get().stream()).collect(Collectors.toList());
    }

}

それでおしまい!これで、JAX-RS エンドポイントが Swagger によって文書化されます。次のサンプル エンドポイントを使用しました。

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Component;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Component
@Path("/hello")
@Api
public class Endpoint {

    @GET
    @ApiOperation("Get message")
    @Produces(MediaType.TEXT_PLAIN)
    public String message() {
        return "Hello";
    }

}

サーバーを起動してhttp://localhost:8080/swagger-ui.html にアクセスすると、JAX-RS エンドポイントのドキュメントが表示されます。ページ上部のコンボボックスを使用して、Spring MVC エンドポイントのドキュメントに切り替えます

ここに画像の説明を入力

于 2016-03-19T17:38:38.713 に答える