SpringFox 找不到 jax-rs 端点

2023-11-26

解决后使用 Springfox 在 Spring 应用程序中记录 jax-rs 服务,我现在发现SpringFox的JSON回复没有显示任何API:

{
  "swagger": "2.0",
  "info": {
    "description": "Some description",
    "version": "1.0",
    "title": "My awesome API",
    "contact": {
      "name": "[email protected]"
    },
    "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("[email protected]")
                .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 库可以解决这个问题,或者改进解决方案吗?


默认情况下,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 应用程序中启用了带有 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 端点都将位于/apicontext - 否则会与 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());
    }

}

就是这样!现在,Swagger 将记录您的 JAX-RS 端点。 我使用了以下示例端点:

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringFox 找不到 jax-rs 端点 的相关文章

随机推荐

  • React Native 无限滚动

    我试图获得无限滚动的最小示例 所以我有这个 var React require react native var StyleSheet View Image ListView React var data id 1 profile pict
  • PostgreSql:禁止更新列:如何?

    使用 PostgreSql 可以在没有触发器的情况下不允许更新列 只允许插入 完全未经测试 但由于 Postgres SQL 支持列级权限 看起来可能是这样 http www postgresql org docs current stat
  • N 元组与对

    在 Ocaml 中 具有不同元数的元组具有不同的类型和值构造函数 let a 1 2 3 val a int int int 1 2 3 let b 1 2 3 val b int int int 1 2 3 请注意 第二个示例 b 比第一
  • 配置 ELMAH:无法识别的配置部分错误

    Setup 视窗XP NET框架3 5 SP1 ASP NET MVC 版本 1 我一直在尝试按照以下说明设置 ELMAHhttp code google com p elmah wiki MVC但按 F5 时出现以下错误 Descript
  • SVG 仅在 Safari 中悬停时调整大小

    我有一个奇怪的问题 svg 在 Safari 中悬停时调整大小 我使用 jquery 的悬停来用稍微不同的 svg 替换页面上的 svg 除了 Safari 之外 此功能在所有浏览器中都可以正常工作 由于某种原因 Safari 会在鼠标悬停
  • 更改密码后 KeyStore getEntry 返回 null

    您好 我有一个程序需要在密钥库中存储密钥 我生成一对密钥并签署一个值 这始终可以完美运行 当用户进入首选项并更改密码或将密码模式更改为 pin 模式时 就会出现问题 之后 当我尝试访问私钥时 密钥库返回给我一个空值 我知道密钥存储值是用解锁
  • Julia:添加包的问题 (BinDeps)

    我是 Julia 包管理器的新手 在安装 GLPK 和 LinProgGLPK 时遇到问题 我已经跑了Pkg Init 并已成功安装 Curl 使用Pkg add Curl 但是 当我尝试安装 GLPK 或 LinProgGLPK 使用Pk
  • PHP 的基本身份验证产生无限循环

    由于某种原因 我无法在我的服务器上使用 PHP 进行基本身份验证 我正在使用手册页中的确切代码
  • 如何扩展可用 Java 语言环境列表

    我正在寻找一种方法将更多区域设置添加到 Java 1 6 中可用的区域设置中 但我想要创建的区域设置没有 ISO 3166 国家 地区代码 也没有 ISO 639 语言代码 无论如何 有什么办法可以做到这一点吗 我想添加的区域设置仅在语言名
  • 递归块内的 ARC 行为

    我制作了这两个实用函数 void dispatch void f afterDelay float delay dispatch after dispatch time DISPATCH TIME NOW int64 t delay NSE
  • Appengine - 使用 https 的本地开发服务器

    目标 使用 App Engine 开发服务器缩短开发反馈周期 为了我的使用 它必须作为公共 HTTPS 地址可用 App Engine 开发服务器仅支持 HTTP 这个怎么做 使用 ngrok 将本地开发环境公开为 https 公开可用地址
  • PyLint 错误空白配置

    有没有办法配置检查bad whitespace检查 PyLint 我目前可以禁用检查 但我宁愿强制执行空白约定而不是禁用它 您可以使用两个选项 全局禁用错误空白警告 pylint disable C0326 使用 Pylint 配置文件 p
  • 为什么固定定位会改变元素的宽度?

    我有一个 div 其宽度设置为100 当我添加position fixed到它 宽度变成16px larger 我注意到身体上有8px各边都有边距 所以我猜position fixed以某种方式忽略了包含它的正文标签的边距 我看了看MDN
  • 如何创建具有可变数量参数的函数?

    如何在 Rust 中创建具有可变数量参数的函数 就像这段Java代码 void foo String args for String arg args System out println arg 一般来说 你不能 Rust 不支持可变参数
  • 为什么我们真的需要向下转型? [复制]

    这个问题在这里已经有答案了 我试图弄清楚为什么我需要向下转型 我重新阅读了拼贴画中的笔记 发现了下面的例子 class Student class Graduate exteds Student getResearchTopic this
  • 如何仅在 bean 存在时才注入它

    我有以下 Spring 上下文文件结构 gt 代表 包含 A1 xml gt B xml C xml A2 xml gt B xml C xml定义一个beanc B xml定义一个beanb依赖于c 显然这对于 A2 来说是失败的 因为没
  • TextRenderer.MeasureText 和 Graphics.MeasureString 大小不匹配

    这不是舍入问题 差异 5 像素 测试用例字符串 MACD 26 12 9 0 000016 e Graphics MeasureString MACD 26 12 9 0 000016 SystemFonts DefaultFont Wid
  • 如何在 C# 中拦截 TAB 键按下以防止标准焦点更改

    通常 当按 TAB 键时 您会将焦点更改为给定 Tab 键顺序中的下一个控件 我想防止这种情况发生 并让 TAB 键执行其他操作 就我而言 我想将焦点从组合框更改为完全不同的控件 我无法通过设置 Tab 键顺序来做到这一点 我需要以编程方式
  • 如何更好地利用 MSI 文件

    你可能知道 msiexec是一个命令行应用程序 可用于安装 MSI 文件 您可能知道 您可以在静默或隐形模式下运行它 如果安装程序要求用户回答有关要安装哪些部分的具体问题 是否可以通过某种方式在 msiexec 命令行中添加一系列选项来执行
  • SpringFox 找不到 jax-rs 端点

    解决后使用 Springfox 在 Spring 应用程序中记录 jax rs 服务 我现在发现SpringFox的JSON回复没有显示任何API swagger 2 0 info description Some description