복붙노트

[SPRING] Jersey 2와 Spring을 Java 기반 구성과 통합

SPRING

Jersey 2와 Spring을 Java 기반 구성과 통합

저지 2.10과 저지 스프링 3, 스프링 4를 사용하고 있습니다. 저지 자원뿐만 아니라 다른 곳에서 DI (기본적으로 서비스)를 달성하고 Java Configuration을 통해 Spring Bean을 만들고 싶습니다.

현재이 작업을 수행 할 수있는 방법을 찾을 수 없습니다. 어떤 생각을하는 방법이?

내 web.xml은 다음과 같이 보입니다.

<web-app>
    <display-name>Restful Web Application</display-name>
    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>
             org.glassfish.jersey.servlet.ServletContainer 

        </servlet-class>
        <init-param>
            <param-name>
                jersey.config.server.provider.packages
            </param-name>
            <param-value>com.xyz</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/application-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

해결법

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

    1.웹 앱 :

    웹 앱 :

    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
          org.springframework.web.context.support.AnnotationConfigWebApplicationContext
      </param-value>
    </context-param>
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>xxx.xxx.configuration.ApplicationConfiguration</param-value>
    </context-param>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <servlet>
        <servlet-name>SpringApplication</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>xxx.xxx.controllers.HelloController</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>SpringApplication</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    

    Java 기반 구성 :

    @Configuration
    public class ApplicationConfiguration {
      @Bean
      HelloService helloService () {
        return new HelloServiceImpl();
      }
    }
    

    간단한 컨트롤러 :

    @Component
    @Path("/helloController")
    public class HelloController {
    
      @Autowired
      @Qualifier("helloService")
      private HelloService helloService ;
    
    
       @GET
       @Path("/hello")
       public String hello() {
        helloService.service();
      }
    }
    

    시험용:

    localhost : 8080 / [AppName] / helloController / hello

    오래된 Spring 의존성을 배제하는 것에 대해 기억해 두십시오. 그렇지 않으면 충돌이 발생할 수 있습니다. 아래 예제 또는 DependencyManagement를 통해 이와 동일하게 수행 할 수 있습니다.

    <dependencies>
    
        <!-- Jersey -->
    
        <dependency>
            <groupId>org.glassfish.jersey.ext</groupId>
            <artifactId>jersey-spring3</artifactId>
            <version>2.11</version>
            <exclusions>
                <exclusion>
                    <artifactId>spring-context</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-beans</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-core</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-web</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>jersey-server</artifactId>
                    <groupId>org.glassfish.jersey.core</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>
                        jersey-container-servlet-core
                    </artifactId>
                    <groupId>org.glassfish.jersey.containers</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>hk2</artifactId>
                    <groupId>org.glassfish.hk2</groupId>
                </exclusion>
            </exclusions>
        </dependency>
    
        <!-- Spring 4 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.0.6.RELEASE</version>
        </dependency>
    
    </dependencies>
    
  2. ==============================

    2.ContextLoaderListener를 이미 초기화 했으므로 WebApplicationContext를 사용하여 모든 응용 프로그램 포인트에서 Bean을 검색하면됩니다.

    ContextLoaderListener를 이미 초기화 했으므로 WebApplicationContext를 사용하여 모든 응용 프로그램 포인트에서 Bean을 검색하면됩니다.

    WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    SomeBean someBean = (SomeBean) ctx.getBean("someBean");
    

    또는 Jersey가 이미 Spring DI를 지원하고 있으므로 주석 기반 검색을 사용할 수 있습니다. 빈을 메인 애플리케이션 진입 점 아래에 등록해야합니다. 아래의 예제에서 그 엔트리 포인트는 some.package.MyApplication이 될 것이고 서블릿 컨테이너의 으로 제공되어야한다.

    <servlet>
      <servlet-name>SpringApplication</servlet-name>
      <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
      <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>some.package.MyApplication</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
    </servlet>
    

    애플리케이션에 bean을 등록하십시오.

    package some.package;
    
    import org.glassfish.jersey.server.ResourceConfig;
    import org.glassfish.jersey.server.spring.scope.RequestContextFilter;
    
    public class MyApplication extends ResourceConfig {
      public MyApplication () {
        register(RequestContextFilter.class);
        register(SomeBean.class);
        // ...
      }
    }
    

    여기서 Jersey Git repo에서 실행할 준비가 된 예제를 살펴볼 수 있습니다.

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

    3.다음은 다양한 자습서에서 시작하여 내가 찾은 것입니다. 다른 답변들과 결합하여 완전한 예제가 있어야합니다.

    다음은 다양한 자습서에서 시작하여 내가 찾은 것입니다. 다른 답변들과 결합하여 완전한 예제가 있어야합니다.

    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRegistration;
    
    import com.sun.jersey.spi.spring.container.servlet.SpringServlet;
    import org.springframework.web.WebApplicationInitializer;
    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
    
    public class WebInitializer implements WebApplicationInitializer {
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
            ctx.register(AppConfig.class);
            ctx.setServletContext(servletContext);
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx);
            ServletRegistration.Dynamic servlet = servletContext.addServlet("jersey-serlvet", new SpringServlet());
            servlet.addMapping("/");
            servlet.setLoadOnStartup(1);
        }
    }
    
  4. ==============================

    4.자바 설정으로 할려고하는 사람들을 위해 :

    자바 설정으로 할려고하는 사람들을 위해 :

        public static void main(String[] args) throws IOException {
            HttpServer server = new HttpServer();
            NetworkListener listener = new NetworkListener("grizzly2", "localhost", 2088);
            server.addListener(listener);
    
            WebappContext ctx = new WebappContext("ctx","/");
            final ServletRegistration reg = ctx.addServlet("spring", new SpringServlet());
            reg.addMapping("/*");
            ctx.addContextInitParameter( "contextClass", "org.springframework.web.context.support.AnnotationConfigWebApplicationContext" );
            ctx.addContextInitParameter( "contextConfigLocation", "com.example.AppConfig" );
            ctx.addListener( "org.springframework.web.context.ContextLoaderListener" );
            ctx.addListener("org.springframework.web.context.request.RequestContextListener");
    
            ctx.deploy(server);
    
            server.start();
    
            System.in.read();
    
    }
    
  5. from https://stackoverflow.com/questions/25701658/integrating-jersey-2-and-spring-with-java-based-configuration by cc-by-sa and MIT license