SpringFox无法找到JAX-RS终端点。

7

在解决了如何使用Springfox来记录Spring应用中的jax-rs服务后,我发现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库能解决这个问题吗,或者会提高解决方案的效率呢?

1
很不幸,springfox并不支援jax-rs标注。我想你最好使用swagger-core库。 - Dilip Krishnan
@dilip,Swagger 直接支持 JAX-RS 注解吗? - Don Branson
是的,它支持它。 - Dilip Krishnan
@DilipKrishnan - 谢谢,那正是我需要的帮助。我按照 https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-1.X-Project-Setup-1.5 的步骤进行了操作,然后在其基础上添加了 swagger-ui。 - Don Branson
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结合使用了。 首先,我添加了一些Swagger依赖项以及SpringFox:

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应用程序中启用了JAX-RS(Jersey)和Swagger:

@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


感谢您的回答。我遇到了以下错误:
应用程序启动失败
描述:一个组件需要一个类型为“springfox.documentation.swagger.web.InMemorySwaggerResourcesProvider”的bean,但找不到该bean。操作:请考虑在您的配置中定义一个类型为“springfox.documentation.swagger.web.InMemorySwaggerResourcesProvider”的bean。您在哪里定义了InMemorySwaggerResourcesProvider?
- yeremy
1
@yeremy请确保在您的Spring Boot应用程序类上有@EnableSwagger2注释。 - bedrin
@bedrin:我已经成功在Springfox Swagger 2上列出了Jersey端点。然而,之前可见的授权按钮现在已经消失了...你能帮忙解决一下吗?请注意:当我从下拉菜单中选择默认值时,授权按钮会出现。 - user966506
我可以浏览:http://localhost:5000/swagger-ui.html#/ 它正在为我加载UI,但是我收到了“500:{“timestamp”:“2021-05-25T14:22:23.485 + 0000”,“status”:500,“error”:“内部服务器错误”,“message”:“无可用消息”,“path”:“/ api / swagger.json”} http:// localhost:5000 / api / swagger.json”的错误。此外,当我尝试浏览http:// localhost:5000 / api / swagger.json”时,我收到了java.lang.NullPointerException:null 在org.glassfish.jersey.server.ResourceConfig.getProperties(ResourceConfig.java:751)中。 - Asraful
你有没有使用过AspectJ?你的NPE看起来很像这个问题:https://github.com/spring-projects/spring-boot/issues/6395 - bedrin

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

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接