SpringFox没有找到jax-rs端点

时间:2015-10-01 00:58:14

标签: java jax-rs swagger wordnik springfox

解决Using Springfox to document jax-rs services in a Spring app后,我现在发现SpringFox的JSON回复并未显示任何API:

var tab1 = new ContentView({
   el: '#red'
});
var tab2 = new ContentView({
   el: '#orange'
});
var tab3 = new ContentView({
   el: '#yellow'
});
var tab4 = new ContentView({
   el: '#green'
});

这是springfox-servlet.xml:

{
  "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"
}

这是在属性文件中:

<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配置为使用反射式jax-rs扫描程序查找实现类:

swagger.resourcePackage=org.myapp

这是文档配置:

@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;
    }
}

这是一个带有api注释的示例类:

@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?使用wordnik swagger库会解决这个问题,还是改进解决方案?

2 个答案:

答案 0 :(得分:14)

默认情况下,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端点的文档

enter image description here

答案 1 :(得分:0)

有关授权的其他信息:

  • 如果您想为 Jersey 资源添加身份验证:
BeanConfig swaggerConfig = new BeanConfig();
Swagger swagger = new Swagger();

swagger.securityDefinition("apiKeyAuth", new ApiKeyAuthDefinition("Authorization", In.HEADER));
  
new SwaggerContextService().updateSwagger(swagger);
swaggerConfig.setBasePath("/api");
SwaggerConfigLocator.getInstance().putConfig(SwaggerContextService.CONFIG_ID_DEFAULT, swaggerConfig);

当然这是带有 JWT 令牌的身份验证。如果您需要基本身份验证使用:

swagger.securityDefinition("basicAuth", new BasicAuthDefinition());
  • 如果您需要为 Spring 资源添加身份验证:
@Configuration
public class SwaggerSpringConfig {
    
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.yourPackage"))
                .paths(PathSelectors.any())
                .build()
                .enable(true)
                .securitySchemes(Lists.newArrayList(apiKey()));
    }

    private ApiKey apiKey() {
        return new ApiKey("AUTHORIZATION", "Authorization", "header");
    }

    @Bean
    SecurityConfiguration security() {
        return new SecurityConfiguration(
                null,
                null,
                null,
                null,
                null,
                ApiKeyVehicle.HEADER,
                "Authorization",
                null
        );
    }

}