2013-03-29 1 views
8

나는 쉽게 노출 할 수있는 기본 JAXRS 서비스를 가지고 있지만, 일단 의존성 주입 API를 사용하기를 원한다면 Google Guice가 최고가 될 것으로 의심됩니다. 이를 염두에두고, 나는 그것을 통합하는 것을 시도했다, 그러나 문서는가는 조금 무거운 내가Google Guice를 JaxRS (저지)와 함께 사용하는 방법

  • 의 Web.xml
  • 문맥의 오른쪽 조합을 시도하고 찾아 주위를 사냥하는 것을 봤는데 리스너 (I 사용해야 ServletContainer 또는 GuiceContainer)
  • 서비스
  • @Singleton 또는 @Request 또는 아무것도 서비스 주석할지 여부
  • (내가 @Singleton와 주석을해야 - 문서 내가해야 말을하지만 기본값이 범위를 요청 말한다)
  • 다음과 같이 생성자 매개 변수에 주석을 추가할지 여부 : @InjectParam

하지만 현재 Google Guice에서 오류가 발생하며 @InjectParam 특수 효과를 사용하는지 여부에 따라 변경됩니다. 그때 @InjectParam와 주석을하면 내가 주석을하지 않는 경우

나는 나는이 내 web.xml을

<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 
    <filter> 
     <filter-name>guiceFilter</filter-name> 
     <filter-class>com.google.inject.servlet.GuiceFilter</filter-class> 
    </filter> 

    <filter-mapping> 
     <filter-name>guiceFilter</filter-name> 
     <url-pattern>/*</url-pattern> 
    </filter-mapping> 

    <listener> 
     <listener-class>com.hillingar.server.ServletContextListener</listener-class> 
    </listener> 

    <session-config> 
     <session-timeout> 
      30 
     </session-timeout> 
    </session-config> 
</web-app> 

이입니다

Mar 29, 2013 9:54:59 PM com.sun.jersey.spi.inject.Errors processErrorMessages 
SEVERE: The following errors and warnings have been detected with resource and/or provider classes: 
    SEVERE: Missing dependency for constructor public com.hillingar.server.rest.UserService(com.hillingar.server.dao.interfaces.UserDao,com.hillingar.server.SessionUtility) at parameter index 0 
    SEVERE: Missing dependency for constructor public com.hillingar.server.rest.UserService(com.hillingar.server.dao.interfaces.UserDao,com.hillingar.server.SessionUtility) at parameter index 1 

얻을

 Mar 29, 2013 9:52:04 PM com.sun.jersey.spi.inject.Errors processErrorMessages 
    SEVERE: The following errors and warnings have been detected with resource and/or provider classes: 
    SEVERE: The class com.hillingar.server.dao.interfaces.UserDao is an interface and cannot be instantiated. 
    SEVERE: Missing dependency for constructor public com.hillingar.server.SessionUtility(com.hillingar.server.dao.interfaces.UserDao) at parameter index 0 

를 얻을 수 내 ServletContextListener입니다.

package com.hillingar.server; 

import java.util.logging.Logger; 

import javax.servlet.ServletContextEvent; 

import com.google.inject.Guice; 
import com.google.inject.Singleton; 
import com.hillingar.server.dao.jdbcImpl.UserJdbc; 
import com.hillingar.server.dao.interfaces.UserDao; 
import com.sun.jersey.guice.JerseyServletModule; 
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer; 
import com.sun.jersey.spi.container.servlet.ServletContainer; 

public class ServletContextListener implements javax.servlet.ServletContextListener { 

    Logger logger = Logger.getLogger(this.getClass().getName()); 

    @Override 
    public void contextDestroyed(ServletContextEvent arg0) { 
    } 

     /* 
     * Covered in URL 
     * https://code.google.com/p/google-guice/wiki/ServletModule 
     */ 
    @Override 
    public void contextInitialized(ServletContextEvent arg0) { 

      // Note the user of JerseyServletModule instead of ServletModule 
      // otherwise the expected constructor injection doesn't happen 
      // (just the default constructor is called) 
      Guice.createInjector(new JerseyServletModule() { 
       @Override 
       protected void configureServlets() { 

        /* 
        * Note: Every servlet (or filter) is required to be a 
        * @Singleton. If you cannot annotate the class directly, 
        * you must bind it using bind(..).in(Singleton.class), 
        * separate to the filter() or servlet() rules. 
        * Mapping under any other scope is an error. This is to 
        * maintain consistency with the Servlet specification. 
        * Guice Servlet does not support the 
        * deprecated SingleThreadModel. 
        */ 
        bind(SecurityFilter.class).in(Singleton.class); 
        bind(ServletContainer.class).in(Singleton.class); 

        /* 
        * Filter Mapping 
        * 
        * This will route every incoming request through MyFilter, 
        * and then continue to any other matching filters before 
        * finally being dispatched to a servlet for processing. 
        * 
        */ 

        // SECURITY - currently disabled 
        // filter("/*").through(SecurityFilter.class); 

        /* 
        * Registering Servlets 
        * 
        * This registers a servlet (subclass of HttpServlet) called 
        * ServletContainer, the same one that I would have used in 
        * the web.xml file, to serve any web requests with the 
        * path /rest/* i.e. ... 
        * 
         <servlet> 
          <servlet-name>ServletAdaptor</servlet-name> 
          <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> 
          <load-on-startup>1</load-on-startup> 
         </servlet> 
         <servlet-mapping> 
          <servlet-name>ServletAdaptor</servlet-name> 
          <url-pattern>/rest/*</url-pattern> 
         </servlet-mapping> 

        */ 
        serve("/rest/*").with(ServletContainer.class); // JAX-RS 

        // Using this and it starts bitching about 
        // com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes. 
        // So presumably wants an Application class that enumerates 
        // all my services? 
        //serve("/rest/*").with(GuiceContainer.class); 

        /* 
        * Bindings 
        */ 
        bind(UserDao.class).to(UserJdbc.class); 
        bind(SessionUtility.class); 
       } 
      }); 
    } 

} 

이것은

package com.hillingar.server.rest; 

import com.google.inject.Inject; 
import com.google.inject.Singleton; 
import java.util.List; 

import javax.servlet.http.HttpServletRequest; 
import javax.ws.rs.Consumes; 
import javax.ws.rs.GET; 
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.PathParam; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.Context; 
import javax.ws.rs.core.SecurityContext; 

import com.hillingar.server.SessionUtility; 
import com.hillingar.server.dao.interfaces.UserDao; 
import com.hillingar.server.model.User; 
import com.hillingar.server.model.dto.AuthenticationResponse; 

@Path("/user") 
@Produces("application/json") 
@Consumes({"application/xml","application/json"}) 
@Singleton // <-- Added Singleton here 
public class UserService { 

    private UserDao userDao; 
    private SessionUtility sessionManager; 

     /* 
      Error if I annotate with @InjectParam... 

      Mar 29, 2013 9:52:04 PM com.sun.jersey.spi.inject.Errors processErrorMessages 
      SEVERE: The following errors and warnings have been detected with resource and/or provider classes: 
      SEVERE: The class com.hillingar.server.dao.interfaces.UserDao is an interface and cannot be instantiated. 
      SEVERE: Missing dependency for constructor public com.hillingar.server.SessionUtility(com.hillingar.server.dao.interfaces.UserDao) at parameter index 0 

      Error If I don't annotate at all... 
      Mar 29, 2013 9:54:59 PM com.sun.jersey.spi.inject.Errors processErrorMessages 
      SEVERE: The following errors and warnings have been detected with resource and/or provider classes: 
       SEVERE: Missing dependency for constructor public com.hillingar.server.rest.UserService(com.hillingar.server.dao.interfaces.UserDao,com.hillingar.server.SessionUtility) at parameter index 0 
       SEVERE: Missing dependency for constructor public com.hillingar.server.rest.UserService(com.hillingar.server.dao.interfaces.UserDao,com.hillingar.server.SessionUtility) at parameter index 1 

      (both output Initiating Jersey application, version 'Jersey: 1.13 06/29/2012 05:14 PM') 
     */ 
    @Inject 
    public UserService(UserDao userDao, SessionUtility sessionManager) { 
     this.userDao = userDao; 
       this.sessionManager = sessionManager; 
    } 

    @GET 
    public List<User> test(@Context HttpServletRequest hsr) { 
       // USER DAO IS ALWAYS NULL - CONSTRUCTOR INJECTION NOT WORKING 
     User loggedInUser = userDao.findBySessionId(hsr.getSession().getId()); 
       ... 
     return users; 
    } 

} 
+0

에 ServletContextListener를 변경 내 UserService입니까? – condit

+0

나는 매개 변수없는 (그리고 @Inject를 제거한) 생성자를 변경 한 다음 UserDao와 SessionUtility에 대한 getter와 setter (@Inject를 가진 setter)를 생성했습니다. 아직도 전화하지 않습니다. –

+0

오늘 아침 나는 두 가지를 변경했다가 예상대로 작동하기 시작했다. 1) 서블릿 컨텍스트 리스너를 변경하여 GuiceServletContextListener를 확장하고 getInjector 메소드를 재정의했다. 2) injector 내에서 serve ("/ rest/*") .with (GuiceContainer.class); 그리고 이번에는 효과가있었습니다! –

답변

5

당신이 필드로 대신 생성자의 일환으로`UserDao`와`SessionUtility`를 주입하면 어떻게됩니까

package com.hillingar.server; 

import java.util.logging.Logger; 

import javax.servlet.ServletContextEvent; 

import com.google.inject.Guice; 
import com.google.inject.Injector; 
import com.google.inject.Singleton; 
import com.google.inject.servlet.GuiceServletContextListener; 
import com.hillingar.server.dao.jdbcImpl.UserJdbc; 
import com.hillingar.server.dao.interfaces.UserDao; 
import com.hillingar.server.rest.UserService; 
import com.sun.jersey.guice.JerseyServletModule; 
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer; 
import com.sun.jersey.spi.container.servlet.ServletContainer; 

// (1) Extend GuiceServletContextListener 
public class ServletContextListener extends GuiceServletContextListener { 

    Logger logger = Logger.getLogger(this.getClass().getName()); 

    // (1) Override getInjector 
    @Override 
    protected Injector getInjector() { 
     return Guice.createInjector(new JerseyServletModule() { 
      @Override 
      protected void configureServlets() { 
       bind(SecurityFilter.class).in(Singleton.class); 
       bind(UserService.class);// .in(Singleton.class); 
       bind(ServletContainer.class).in(Singleton.class); 

       // (2) Change to using the GuiceContainer 
       serve("/rest/*").with(GuiceContainer.class); // <<<<--- 

       bind(UserDao.class).to(UserJdbc.class); 
       bind(SessionUtility.class); 
      } 
     }); 
    } 
}