You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring6+Jetty12+Jersey3整合报错:Spring上下文查找失败如何解决?

解决Jersey3无法识别Spring6上下文的报错问题

问题根源

你手动创建了AnnotationConfigApplicationContext,但未将其绑定到Jetty的ServletContext中。Jersey的SpringComponentProvider默认会从ServletContext的ROOT WebApplicationContext属性中查找Spring上下文,找不到就会抛出该报错。

解决方案步骤

  1. 确认依赖正确性
    确保引入适配Spring6的Jersey Spring集成依赖,Maven示例:

    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-spring6</artifactId>
        <version>3.1.5</version> <!-- 与你的Jersey主版本保持一致 -->
    </dependency>
    
  2. 绑定Spring上下文到ServletContext
    在创建ServletContextHandler后,将已初始化的Spring上下文存入ServletContext的标准ROOT属性中,让Jersey能够识别。

  3. 显式注册Spring组件提供者
    在ResourceConfig中注册SpringComponentProvider,确保Jersey启用Spring集成逻辑。

修改后的启动代码

import org.springframework.web.context.WebApplicationContext;

public int startServer(int port) throws Exception {
    this.context = new AnnotationConfigApplicationContext(AppConfig.class);

    ResourceConfig rc = new ResourceConfig()
            .packages("com.example.resources")
            .register(JerseyLoggingFilter.class)
            .register(SpringComponentProvider.class)
            .property(ServerProperties.PROCESSING_RESPONSE_ERRORS_ENABLED, true);

    InetSocketAddress bindAddr = new InetSocketAddress(BIND_ADDR, port);
    this.server = new Server(bindAddr);
    ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    contextHandler.setContextPath("/");
    
    // 将Spring上下文绑定到ServletContext的标准属性
    contextHandler.getServletContext().setAttribute(
            WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
            this.context
    );

    ServletHolder servletHolder = new ServletHolder(new ServletContainer(rc));
    contextHandler.addServlet(servletHolder, "/*");
    this.server.setHandler(contextHandler);
    this.server.start();
    port = ((ServerConnector) server.getConnectors()[0]).getLocalPort();
    log.info("server listening on port " + port);
    return port;
}

额外注意事项

  • 确保AppConfig类添加@ComponentScan注解,覆盖你的Jersey资源类所在包(如com.example.resources),让Spring能扫描并管理这些资源类。
  • 所有Jersey资源类需添加Spring注解(如@Component或@RequestScoped),确保Jersey通过Spring上下文获取实例,而非自行创建。

内容的提问来源于stack exchange,提问作者John Calcote

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 08:30:12