将 Jersey 2 和 Spring 与基于 Java 的配置集成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25701658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:57:20  来源:igfitidea点击:

Integrating Jersey 2 and Spring with Java Based Configuration

javaspringrestjersey-2.0

提问by beinghuman

I am using Jersey 2.10 and jersey-spring3 and Spring 4. I want to achieve DI(basically services) in jersey resources as well as in other places and want to create Spring Beans through Java Configuration.

我正在使用 Jersey 2.10 和 jersey-spring3 和 Spring 4。我想在 jersey 资源以及其他地方实现 DI(基本服务),并希望通过 Java 配置创建 Spring Bean。

Currently,I am not able to find out any way to do this. Any idea how to do this?

目前,我无法找到任何方法来做到这一点。知道如何做到这一点吗?

my web.xml looks like this

我的 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>

采纳答案by Marek R

web-app:

网络应用程序:

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

JavaBased Configuration:

基于 Java 的配置:

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

and simple controller:

和简单的控制器:

@Component
@Path("/helloController")
public class HelloController {

  @Autowired
  @Qualifier("helloService")
  private HelloService helloService ;


   @GET
   @Path("/hello")
   public String hello() {
    helloService.service();
  }
}

for testing:

用于检测:

localhost:8080/[AppName]/helloController/hello

本地主机:8080/[AppName]/helloController/hello

remember about excluding old Spring dependencies you may have some conflicts if you don't. You can do this same as on the example below or through DependencyManagement.

记住要排除旧的 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>

回答by tmarwen

Old Fashioned way:

老式方式:

Since you have already initialized the ContextLoaderListenera simple trick is to use the WebApplicationContextto retrieve your beans at any application point:

由于您已经初始化,ContextLoaderListener一个简单的技巧是WebApplicationContext在任何应用程序点使用检索您的 bean:

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

Jersey Support:

泽西岛支持:

Or you can use the annotation based discovery, since Jerseyhas already support for Spring DI. You have to register your beans under your main application entry point. That entry point, in below example will be some.package.MyApplication, should be provided as an <init-param>of the servlet container:

或者您可以使用基于注解的发现,因为Jersey已经支持Spring DI。您必须在主应用程序入口点下注册您的 bean。该入口点,在下面的例子中some.package.MyApplication,应该作为<init-param>servlet 容器的一个提供:

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

Register you beans in your application:

在您的应用程序中注册您的 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);
    // ...
  }
}

Hereyou can take a look to a ready to run example from Jersey Git repo.

在这里,您可以查看 Jersey Git 存储库中准备运行的示例。

回答by oldfashionednewidea

Here is something that I found starting from various tutorials. Combined with other answers you should have a complete example.

这是我从各种教程中发现的东西。结合其他答案,您应该有一个完整的示例。

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

回答by Georgi Staykov

For those trying to do it with Java config:

对于那些尝试使用 Java 配置执行此操作的人:

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

}