복붙노트

[SPRING] 저지 - 스프링 3 인스턴스화 봄 관리 빈 (null!)

SPRING

저지 - 스프링 3 인스턴스화 봄 관리 빈 (null!)

나는 이것이 내 경력에서 다루어 본 시간 낭비의 측면에서 가장 큰 문제라는 것을 먼저 지적하고 싶다. (2 일이 지나면 곧바로 진도가 0이됩니다.) 시도한 모든 "해결 방법"또는 "해결 방법"은 효과가 없었기 때문에 막혔고 도움이 절실합니다.

간단히 말해서, Jersey / HK2는 이미 Spring에서 인스턴스화 된 후에 저의 spring 관리 bean을 인스턴스화하는 것처럼 보입니다. 저지 봄 3은 저의 작업을 수행하지 않고 적어도 현재의 설정은 아닙니다. 또는 지금까지 시도한 설정의 ~ 50 순열 중 하나를 선택합니다.)

비어있는 생성자를 사용하면 런타임시 해당 리소스 필드가 null입니다.

나는이 온라인 예제를 본질적으로 복사하고 있기 때문에 현재 설정이 작동하지 않는 이유를 모르겠다.

어떤 도움을 주셔서 감사합니다!

- - - - - Pom.hml - - - - - -

<!-- ... -->

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

업데이트 - 발견 :

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 # ApplicationContext에서 ApplicationContext를 찾을 수 없습니다.

해결법

  1. ==============================

    1.무엇이 먼저로드됩니까? 봄이나 저지? SpringComponentProvider가 WebApplicationContextUtils.getWebApplicationContext (sc);를 호출 할 때 Spring 컨텍스트가 초기화되지 않았을 수 있습니다. Spring의 ContextLoaderListener를 사용하여 App이 배치 된 직후 Spring이 초기화를 수행하도록하십시오.

    무엇이 먼저로드됩니까? 봄이나 저지? SpringComponentProvider가 WebApplicationContextUtils.getWebApplicationContext (sc);를 호출 할 때 Spring 컨텍스트가 초기화되지 않았을 수 있습니다. Spring의 ContextLoaderListener를 사용하여 App이 배치 된 직후 Spring이 초기화를 수행하도록하십시오.

    jersey-spring3 라이브러리에서 경험하는 것과 동일한 문제가 많이 발생했습니다. 내 Spring ApplicationContext를 찾는 데 문제가있어 (일반적인 상황에서 멈추는 것처럼 보임) 일반 매개 변수를 인수로 사용하는 setter를 주입했다.

    앱 컨텍스트 문제를 극복했다면 어쨌든 내가 가지고있는 것을 생각하지 않아도됩니다. XML로 ViewResource와 LocationResource 빈을 정의했다. 내가 알 수 있듯이, Jersey는 리소스 클래스에 @Component 주석이 달린 경우에만 Spring에서 리소스 인스턴스를 가져온다. org.glassfish.jersey.server.spring.SpringComponentProvider, 특히 component.isAnnotationPresent (Component.class)를 살펴보십시오.

    // detect JAX-RS classes that are also Spring @Components.
    // register these with HK2 ServiceLocator to manage their lifecycle using Spring.
    @Override
    public boolean bind(Class<?> component, Set<Class<?>> providerContracts) {
    
        if (ctx == null) {
            return false;
        }
    
        if(component.isAnnotationPresent(Component.class)) {
            DynamicConfiguration c = Injections.getConfiguration(locator);
            String[] beanNames = ctx.getBeanNamesForType(component);
            if(beanNames == null || beanNames.length != 1) {
                LOGGER.severe(LocalizationMessages.NONE_OR_MULTIPLE_BEANS_AVAILABLE(component));
                return false;
            }
            String beanName = beanNames[0];
    
            ServiceBindingBuilder bb = Injections.newFactoryBinder(new SpringComponentProvider.SpringManagedBeanFactory(ctx, locator, beanName));
            bb.to(component);
            Injections.addBinding(bb, c);
            c.commit();
    
            LOGGER.config(LocalizationMessages.BEAN_REGISTERED(beanName));
            return true;
        }
        return false;
    }
    

    관련없는 문제는 모든 JAX-RS 주석을 인터페이스로 옮기고 싶다는 것이 었습니다. 내가 그것을 시도 할 때마다 "com.foo.ResourceInterface에 적합한 생성자를 찾을 수 없습니다."라는 메시지가 나타납니다.

    결국 저지 - 스프링 3을 사용하지 않고 내 자신의 저지를 스프링 커넥터로 굴려서 모든 문제를 해결했습니다. 여기 내가 한 일이있다.

    내 javax.ws.rs.Application은 다음과 같습니다.

    public class RestConfig extends ResourceConfig {
    private static final Log log = LogFactory.getLog(RestConfig.class);
    
    
    @Inject
    public RestConfig(ServiceLocator locator) {
        super();
        // specific to my app. get your spring beans however you like
        Collection<Object> beans = BeanLocator.beansByAnnotation(RestResource.class);
    
        DynamicConfiguration c = Injections.getConfiguration(locator);
    
    
        for (Object bean : beans)
        {
                        // tell jersey to use a factory for any interface that the bean implements.  since your resources don't implement interfaces, 
                        // you'll want to do something a bit different here.
            for (Class<?> currentInterface : bean.getClass().getInterfaces())
            {
                if (log.isTraceEnabled())
                    log.trace("binding " + currentInterface.getSimpleName() + " to Spring managed bean");
    
                ServiceBindingBuilder<Object> bb = Injections.newFactoryBinder(new StaticLookupFactory(locator, bean));
                bb.to(currentInterface);
                        Injections.addBinding(bb, c);
            }
        }
    
                // commit the changes to the HK2 container (don't skip this step!)
                c.commit();
    
        property("jersey.config.disableMoxyJson.server", true);
        packages("com.foo.web.rest");
    
        register(MoxyXmlFeature.class);
    }
    
    
    // a "factory" where the provide() method returns the spring managed bean
        // that was passed to the constructor.
    private static class StaticLookupFactory implements Factory<Object> {
    
        private ServiceLocator locator;
        private Object bean;
    
        StaticLookupFactory(ServiceLocator locator, Object bean)
        {
            this.locator = locator;
            this.bean = bean;
        }
    
        @Override
        public Object provide() {
                        // inject this annotated with @Context, @Inject, etc
            locator.inject(bean);
            return bean;
        }
    
        @Override
        public void dispose(Object instance) {
        }
    
    }
    }
    

    BeanLocator는 필자가 작성한 유틸리티 클래스로, autowiring을 사용할 수 없을 때 정적 메소드를 사용하여 bean 인스턴스를 쉽게 잡을 수있게 해준다. 예를 들어, Spring 관리 Bean 외부에서 작업 할 때. 너무 많지는 않습니다.

    public static Collection<Object> beansByAnnotation(Class<? extends Annotation> annotation)
    {
        return applicationContext.getBeansWithAnnotation(annotation).values();
    }
    

    RestResource는 Google 앱에서만 제공됩니다. @Component, @Service 등과 같이 작동하는 사용자 정의 스테레오 타입입니다.

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Component
    public @interface RestResource {
        String value() default "";
    }
    

    Jersey를 사용하면 org.glassfish.jersey.server.spring.ComponentProvider의 사용자 정의 구현을 등록하여 직접 자원의 라이프 사이클을 관리 할 수 ​​있습니다. 나는 그것을 시도했으나 내가 한 것에 상관없이 내 구현을 인식 할 수 없었다.

    또 다른 한가지주의 할 점은 저지 종속성 주입 메커니즘을 활성화하는 locator.inject (bean) 호출은 @Inject로 표시된 모든 것을 처리한다는 것입니다. 클래스 내에서 @Autowired를 사용하거나 Bean을 XML로 구성하여 Spring과 Jersey가 @Inject로 주석 처리 된 값을 해석하지 않도록하십시오.

  2. ==============================

    2.사용자 정의 비동기 ContextLoader가 있으므로 중간 솔루션은 Jersey-Spring3 소스에서 전체 해킹을 수행하여 응용 프로그램이 사용자 정의 구성 요소 공급자가 초기화되기 전에 초기화 될 때까지 기다려야했습니다.

    사용자 정의 비동기 ContextLoader가 있으므로 중간 솔루션은 Jersey-Spring3 소스에서 전체 해킹을 수행하여 응용 프로그램이 사용자 정의 구성 요소 공급자가 초기화되기 전에 초기화 될 때까지 기다려야했습니다.

    추신 이와 같은 일을해야하는 불쌍한 영혼을 위해 META-INF / settings에 SpringComponentProvider 설정이 포함되어 있는지 확인하십시오.

    (2014-04-18) @Scott에 대한 정교함

    이것은 끔찍한 해킹이며 다른 모든 시도가 실패했을 때 최후의 수단으로 시도 할 것입니다. 내 경우처럼. 또한 이와 같은 시도를하기 전에 문제에 대해 저지 메일 링 그룹에 문의 할 것입니다.

    그것이 ... 내 문제를 해결하기 위해 한 일이다.

    ===>

      /**
       * 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!");
          }
        }
      }
    

    ContextLoaderHttpInterceptor는 HTTP 서블릿이므로 isNotStarted는 사용자 정의 ContextLoader (비동기로 발생하는)가 아직로드되지 않은 경우 true를 반환합니다.

    사용자 정의 비동기 ContextLoader는 서버가 부팅되는 동안 UI에 "로드 중"페이지를 표시 할 수있는 행을 따라 어떤 이유로 인해 누군가가 언젠가는 배치했습니다. (아마도이 ​​UI "기능"을 추가하는 올바른 방법은 아니지만 코드가 거기에 있었고 UI가 그것에 의존했기 때문에이를 처리해야했습니다 ...)

    이 부분은 여러분에게 직접적으로 적용되지 않기 때문에, 핵심은 SpringComponentProvider (여기에서)를 통해 디버그하고 ClassPathXmlApplicationContext의 값을 살펴 보는 것이다. 그것이 null 인 경우, 우리의 경우처럼 null 인 이유를 알아 내야하며이 구성 요소를 초기화하기 전에로드 할 ContextLoader를 기다려야합니다.

    ==>

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

    ==>

    /**
     * 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()));
      }
    }
    

    그것은 "그것"입니다. 자랑스러워할만한 해결책은 아니지만, 필자가 생각한 것처럼 절망적 인 자세를 취한다면, 아마도 그 기회를 놓치지 않을 것입니다.

  3. ==============================

    3.이 문제를 이해하는 데 중요한 메시지입니다. 이것은 Spring이 올바르게 초기화되지 않았 음을 나타냅니다.

    이 문제를 이해하는 데 중요한 메시지입니다. 이것은 Spring이 올바르게 초기화되지 않았 음을 나타냅니다.

    SEVERE: Spring context lookup failed, skipping spring component provider initialization.
    

    (사이드 노트 : Spring이 초기화에 실패했기 때문에 @Inject를 해결하는 유일한 JSR-330 구현은 HK2입니다. 이것이 다른 이슈를 보는 이유입니다).

    어쨌든, 문제는 컨테이너가 jersey-spring3의 모든 마법을 발생시키는 주석을 검색하지 않는 것일 수 있습니다.

    이 동작은 Servlet 3.0 사양 (JSR-33, 섹션 1.6.2)의 일부이므로 컨테이너가이를 지원하는지 다시 한 번 확인해야합니다.

    Tomcat의 경우 - Tomcat 7.0.29 이상을 실행하지 않는 한 실제로 Servlet 버전이 web.xml에 지정되어 있는지 확인해야합니다.

    http://tomcat.apache.org/tomcat-7.0-doc/changelog.html#Tomcat_7.0.29_(markt)

    나는 최근에이 문제에 부딪쳤다. 그리고 그것은 견과를 몰아 부쳤고, web.xml을 수정하는 것이 우분투 / Precise에서 업그레이드하는 것보다 쉽다!

    희망이 도움이!

  4. from https://stackoverflow.com/questions/20506644/jersey-spring3-instantiating-spring-managed-bean-null by cc-by-sa and MIT license