jersey-spring3 实例化 Spring 管理的 bean (null!) [英] jersey-spring3 instantiating Spring-managed bean (null!)

查看:20
本文介绍了jersey-spring3 实例化 Spring 管理的 bean (null!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先要指出的是,总的来说,这是我职业生涯中处理过的最大的时间浪费问题.(现在连续两天多,基本上是 0 进度.)我尝试的每一个变通"或解决方案"都没有奏效,所以我被阻止了,非常渴望得到一些帮助.

I first want to point out that this is by and large the biggest problem in terms of time wasted that I have ever dealt with in my career. (Over two days straight now with essentially 0 progress.) Every single "work-around" or "solution" I have attempted hasn't worked, so I am blocked and pretty desperate for some assistance.

简而言之,问题是 Jersey/HK2 似乎总是在 Spring 实例化我的 Spring 管理的 bean 之后实例化它们,这告诉我 jersey-spring3 没有完成它的工作,或者至少在我当前的设置(或者我迄今为止尝试过的大约 50 种设置中的任何一种)没有完成它的工作.

The problem in a nutshell is that Jersey/HK2 seems to always instantiate my Spring-managed beans AFTER they have already been instantiated by Spring, which tells me that jersey-spring3 is not doing its job, or at least not with my current setup (or any of the ~50 permutations of setups I have tried thus far.)

请注意,当我使用空构造函数时,这些资源字段在运行时为空.

我不明白为什么我当前的设置不起作用,因为我实际上是在 复制此在线示例

I do not understand why my current setup doesn't work as I am essentially copying this online example

任何帮助都非常感谢!

- - - - - pom.xml - - - - -

<!-- ... -->

<dependencies>

    <!-- Spring Dependencies -->

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-instrument</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-instrument-tomcat</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
        <exclusions>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-ldap</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-parent</artifactId>
        <version>${spring.version}</version>
        <classifier>tests</classifier>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>${spring.version}</version>
        <classifier>tests</classifier>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-acl</artifactId>
        <version>${spring.version}</version>
        <exclusions>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-support</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework</groupId>
                <artifactId>spring-dao</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- / Spring Dependencies -->

    <!-- API dependencies -->

    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>${jersey.version}</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>${jersey.version}</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-processing</artifactId>
        <version>${jersey.version}</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.test-framework.providers</groupId>
        <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
        <version>2.4</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-spring3</artifactId>
        <version>${jersey.version}</version>
    </dependency>

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>${gson.version}</version>
    </dependency>

    <!-- / API dependencies -->

    <!-- ... -->

</dependencies>

<!-- ... -->

<properties>

    <!-- ... -->

    <spring.version>3.0.5.RELEASE</spring.version>

    <jersey.version>2.4.1</jersey.version>

    <gson.version>2.2.4</gson.version>

    <!-- ... -->

</properties>

<!-- ... -->

- - - - - web.xml - - - - -

<web-app>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/beans.xml</param-value>
    </context-param>

    <!-- ... -->

    <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>fubar.rest.FubarJerseyApplication</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>

    <!-- ... -->

</web-app>

- - - - - beans.xml(上下文配置)- - - - -

<?xml version="1.0" encoding="UTF-8"?>
<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-2.5.xsd">

<!-- ... -->

<!-- beans-outbound-api has configuration for spring-jersey3 to work properly -->
<import resource="beans-api.xml" />

</beans>

- - - - - beans-api.xml - - - - -

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Services -->

    <bean id="locationServiceV1" class="fubar.rest.v1.services.location.impl.LocationServiceV1" />
    <bean id="locationServiceV2" class="fubar.rest.v2.services.location.impl.LocationServiceV2" />

    <bean id="viewServiceV1" class="fubar.rest.v1.services.view.impl.ViewServiceV1" />
    <bean id="viewServiceV2" class="fubar.rest.v2.services.view.impl.ViewServiceV2" />

    <!-- Resources -->

    <bean class="fubar.rest.resources.location.impl.LocationResource">
        <constructor-arg index="0" ref="locationServiceV1" />
        <constructor-arg index="1" ref="locationServiceV2" />
    </bean>

    <bean class="fubar.rest.resources.view.impl.ViewResource">
        <constructor-arg index="0" ref="viewServiceV1" />
        <constructor-arg index="1" ref="viewServiceV2" />
    </bean>

</beans>

代码

- - - - - 资源 (JAX-RS) - - - - -

@Path(RESTLocationResourceV1.PathFields.PATH_ROOT)
@Produces({V1_JSON, APPLICATION_JSON})
public class LocationResource
    extends ResourceBase<LocationResource, ILocationServiceV1, ILocationServiceV2> {

  private static final Logger logger = Logger.getLogger(LocationResource.class);

  @Inject
  public LocationResource(final LocationServiceV1 v1Loc, final LocationServiceV2 v2Loc) {
    super(v1Loc, v2Loc);
    logger.info(format(Messages.INF_INSTANTIATED, "LocationResource"));
  }

  @GET
  @Path(PathFields.SUBPATH_LIST)
  public LocationListV1 listV1(@HeaderParam(HEADER_API_KEY) String apiKey)
      throws ApplicationException {
    // Implementation
  }

  @GET
  @Path(PathFields.SUBPATH_SEARCH)
  public LocationListV1 searchV1(@HeaderParam(HEADER_API_KEY) String apiKey,
      @QueryParam(QueryFields.QUERY) String likeText) throws ApplicationException {
    // Implementation
  }
}

- - - - - 服务(Spring Bean)- - - - -

public class LocationServiceV1 extends ServiceBaseV1<LocationBean, LocationV1, LocationListV1>
    implements
      ILocationServiceV1 {

  @Autowired
  private LocationDao daoLoc;

  public LocationServiceV1() {
    super(new LocationBeanToJsonTranslatorV1());
  }

  @Override
  public LocationListV1 listV1() throws ApplicationException {
    // Implementation
  }

  @Override
  public LocationListV1 searchV1(String likeText) throws ApplicationException {
    // Implementation
  }
}

(与第 2 版基本相同)

- - - - - 申请(球衣)- - - - -

public class FubarJerseyApplication extends ResourceConfig {

  private static final class Messages {
    static final String INF_STARTING_APPLICATION = "Starting %s!";
  }

  private static final Logger logger = Logger.getLogger(FubarJerseyApplication.class);

  public FubarJerseyApplication() {
    packages("fubar.rest");
    logger.info(format(Messages.INF_STARTING_APPLICATION, this.getClass().getName()));
  }
}

调用(客户端)

curl http://my-ip-address/fubar/api/location/list

(500 内部服务器错误)

org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object
available for injection at Injectee(requiredType=LocationServiceV1,parent=
LocationResource,qualifiers={}),position=0,optional=false,self=false,
unqualified=null,344016971)
at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)
at org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:208)
at org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:225)
at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:329)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:456)
at org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:158)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2350)
at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:612)
at org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:597)
at org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:173)
at org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:185)
at org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:103)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:128)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:131)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:131)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:131)
at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:131)
at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:110)
at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:65)
at org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:250)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:318)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:236)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:983)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:361)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:372)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:335)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:218)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at fubar.server.springframework.SessionFilter.doFilter(SessionFilter.java:44)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at fubar.server.springframework.loader.ContextLoaderHttpInterceptor$LoaderState.filter(ContextLoaderHttpInterceptor.java:75)
at fubar.server.springframework.loader.ContextLoaderHttpInterceptor$StartedState.filter(ContextLoaderHttpInterceptor.java:120)
at fubar.server.springframework.loader.ContextLoaderHttpInterceptor.doFilter(ContextLoaderHttpInterceptor.java:62)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.jk.server.JkCoyoteHandler.invoke(JkCoyoteHandler.java:190)
at org.apache.jk.common.HandlerRequest.invoke(HandlerRequest.java:311)
at org.apache.jk.common.ChannelSocket.invoke(ChannelSocket.java:776)
at org.apache.jk.common.ChannelSocket.processConnection(ChannelSocket.java:705)
at org.apache.jk.common.ChannelSocket$SocketConnection.runIt(ChannelSocket.java:898)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:690)
at java.lang.Thread.run(Thread.java:662)

API 日志

Dec 10, 2013 13:36:28 INFO  [main] fubar.rest.FubarJerseyApplication
     - Starting fubar.rest.FubarJerseyApplication!
Dec 10, 2013 13:38:06 INFO  [pool-1-thread-1] resources.location.impl.LocationResource
     - LocationResource has been instantiated
Dec 10, 2013 13:38:06 INFO  [pool-1-thread-1] resources.view.impl.ViewResource
     - ViewResource has been instantiated

<小时>

更新——发现这个:


Update -- found this:

Dec 10, 2013 1:36:42 PM org.glassfish.jersey.server.ApplicationHandler initialize
INFO: Initiating Jersey application, version Jersey: 2.4.1 2013-11-08 12:08:47...
Dec 10, 2013 1:36:43 PM org.glassfish.jersey.server.spring.SpringComponentProvider initialize
SEVERE: Spring context lookup failed, skipping spring component provider initialization.
Dec 10, 2013 1:38:00 PM com.sun.xml.bind.v2.runtime.reflect.opt.Injector inject

...所以在 SpringComponentProvider#initialize.

推荐答案

我们有一个自定义的异步 ContextLoader,因此临时解决方案需要在 Jersey-Spring3 源在自定义组件提供程序初始化之前等待应用程序初始化.

We have a custom, asynchronous ContextLoader, so the interim solution required placing a total hack in the Jersey-Spring3 source to wait for the application to initialize before the custom component provider initializes.

附:对于任何发现自己不得不做这样的事情的可怜人,确保 META-INF/settings 包含 SpringComponentProvider 配置.

P.S. For any poor soul who finds themselves having to do something like this, make sure META-INF/settings contains the SpringComponentProvider configuration.

(2014-04-18) 为@Scott 详细说明

(2014-04-18) Elaborating for @Scott

请注意,这是一个可怕的 hack,当所有其他尝试都失败时,我只会尝试这样的事情作为最后的手段,就像我的情况一样.另外,在尝试这样的事情之前,我会向泽西邮件组咨询您的问题.

Note that this is a terrible hack and I would only attempt such a thing as a last resort when all other attempts have failed, like in my case. Also I would consult the Jersey mailing group about your problem before attempting anything like this.

也就是说……这就是我为解决我的问题所做的:

That said... this is what I did to solve my problem:

  • 将 spring-jersey3 的源代码直接复制到我的应用程序/服务器中,根据许可证修改每个文件的标头并使用适当的标签;

  • Literally copied the source code of spring-jersey3 into my application/server, modifying the header of every file with the appropriate tags as per the license;

创建了以下类--

===>

  /**
   * Hack class for RN-8979.
   *
   * @author ryan
   *
   */
  public class ContextLoadWaiter {

    private static final Logger logger = Logger.getLogger(ContextLoadWaiter.class);

    public void doWait() {

      try {
        while (ContextLoaderHttpInterceptor.isNotStarted()) {
          logger.info("Waiting for ContextLoader to start...");
          Thread.sleep(1000);
        }
      } catch (InterruptedException e) {
        logger.error("SpringComponentProvider was interrupted!");
      }
    }
  }

请注意,这是特定于 *our* 代码库的,因为 ContextLoaderHttpInterceptor 是一个 http servlet,其中 isNotStarted 返回 true 如果我们的自定义 ContextLoader(恰好是异步的)尚未加载.

Note that this is specific to *our* code-base as ContextLoaderHttpInterceptor is an http servlet where isNotStarted returns true if our custom ContextLoader (which happens to be asynchronous) is not yet loaded.

自定义异步 ContextLoader 是有人出于某种原因在服务器启动时允许 UI 显示正在加载"页面的原因而放置的.(可能不是添加这个 UI功能"的正确方法,但是代码在那里并且 UI 依赖于它,所以我不得不处理它......)

The custom asynchronous ContextLoader was put in place sometime by somebody for some reason along the lines of allowing the UI to display a "loading" page while the server boots up. (Probably not the correct way to add this UI "feature", but the code was there and the UI depended on it, so I had to deal with it...)

由于这部​​分不会直接适用于你,关键是通过 SpringComponentProvider 调试(来自 here) 并查看 ClassPathXmlApplicationContext.如果它是 null,就像我们的例子一样,那么你需要弄清楚它为什么是 null 并等待你使用的任何 ContextLoader在初始化此组件之前加载.

Since this part will not apply directly to you, the key thing is to debug through SpringComponentProvider (from here) and look at the value of the ClassPathXmlApplicationContext. If it is null, as it is in our case, then you need to figure out why it is null and wait on whatever ContextLoader you use to load before you initialize this component.

  • 将这条 hacky 行放在 SpringComponentProvider --

==>

  ...

  private final ContextLoadWaiter waiter = new ContextLoadWaiter();

  ...

  @Override
  public void initialize(ServiceLocator locator) {

    waiter.doWait(); // Wait on our asynchronous context loader.

    this.locator = locator;

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Context lookup started");
    }

    ...

  • 创建了这个文件:META-INF/services/org.glassfish.jersey.server.spi.ComponentProvider,其内容是 SpringComponentProvider 的完全限定类路径,例如com.company.server.nbi.rest.internal.jspring.SpringComponentProvider

    • Created this file: META-INF/services/org.glassfish.jersey.server.spi.ComponentProvider with the contents being the fully qualified classpath to the SpringComponentProvider, e.g. com.company.server.nbi.rest.internal.jspring.SpringComponentProvider

      添加了自定义 Jersey-spring3 包作为包在应用中进行扫描;见下文...

      Added the custom Jersey-spring3 package as a package to scan in the application; see below...

      ==>

      /**
       * Application configuration.
       *
       * @author ryan
       *
       */
      public class MyJerseyApplication extends ResourceConfig {
      
        private static final class Messages {
          static final String INF_STARTING_APPLICATION = "Starting %s!";
        }
      
        private static final Logger logger = Logger.getLogger(MyJerseyApplication.class);
      
        public MyJerseyApplication() {
      
          packages(
          /* Internal providers */
          "com.company.server.nbi.rest.providers",
          /* Internal filters */
          "com.company.server.nbi.rest.filters",
          /* Spring injection support */
          "com.company.server.nbi.rest.internal.jspring", // HERE!!!
          /* Json providers */
          "com.fasterxml.jackson.jaxrs.json",
          /* Jackson exception mappers */
          "com.fasterxml.jackson.jaxrs.base");
      
          /* Resources */
          register(ResourceA.class);
          register(ResourceB.class);
          register(ResourceC.class);
      
          /* Miscellaneous features */
          register(MultiPartFeature.class);
          register(LoggingFilter.class);
      
          logger.info(format(Messages.INF_STARTING_APPLICATION, this.getClass().getName()));
        }
      }
      

      那就是它".绝对不是一个值得骄傲的解决方案,但如果你像我一样处于绝望模式,试一试可能没有什么坏处.

      That's "it". Definitely not a solution to be proud of, but if you are in desperation mode like I was, it probably doesn't hurt to give it a shot.

      这篇关于jersey-spring3 实例化 Spring 管理的 bean (null!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆