How to use Jersey 2 with Spring IoC container

独自空忆成欢 提交于 2019-12-18 11:27:43

问题


What is the best way to enable injection of spring beans into Jersey 2? Jersey seems to not support this natively.

What is needed to wire the 2 frameworks together? In pom.xml and web.xml?


回答1:


You should be able to annotate jersey components and then use annotations to inject the beans.

@Service //(or @Component)
public class MyJerseyService {

    @Autowired
    private MyObj mySpringBean

}



回答2:


Jersey 2.3 has now spring support:

https://jersey.github.io/documentation/latest/user-guide.html#spring

As stated in the documentation

The Spring extension module configuration is based on annotations

So you have to tell spring to scan your classpath, for example:

<context:component-scan base-package="my.package.to.resources">

and annotate your resource class with a spring annotation (I advise to use @Component, and then specify the jersey resource scopes @Singleton/@PerLookup/@RequestScoped )

@Component
@Singleton
@Path("example")
public class Example {

    //Spring beans can't be injected directly into JAX-RS classes by using Spring XML configuration
    @Autowired
    private MyOtherBean myOtherBean;

    @GET @Path("hello")
    public String hello() {
        return myOtherBean.hello();
    }
}



回答3:


As of June 2013, Jersey 2.0 has no official Spring support. There are two options:

  1. Use third party code from here https://github.com/marko-asplund/jersey/tree/master/ext/jersey-spring
  2. Wait until HK2 spring bridge becomes stable and documented https://java.net/jira/browse/HK2-40

See also:

http://jersey.576304.n2.nabble.com/Spring-framework-support-for-Jersey-2-td7580673.html

EDIT: Jersey 2.3 has spring support now, see the answer by Fabio below



来源:https://stackoverflow.com/questions/14627409/how-to-use-jersey-2-with-spring-ioc-container

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!