简体   繁体   English

Jersey:将Spring组件注入ContainerRequestFilter

[英]Jersey: Inject Spring component into ContainerRequestFilter

I am using Jersey 1.4 ea together with Spring 3.0 and the jersey-spring integration. 我使用Jersey 1.4 ea和Spring 3.0以及jersey-spring集成。 Integrating Jersey and Spring works fine for resource classes as described here . 整合新泽西州和Spring作为描述资源类工作正常这里 How ever I want to inject a spring component into a ContainerRequestFilter to do some pre-processing of requests. 我怎么想将一个spring组件注入到ContainerRequestFilter中来对请求进行一些预处理。

@Component
public class SecurityFilter implements ContainerRequestFilter {

    // UserManager is a declared spring component
    // Injecting it should work somehow
    @Autowired
    private UserManager userManager;

    @Override
    public ContainerRequest filter(ContainerRequest request) {
        System.out.println(userManager);
        // prints out null on request
    }
}

Both the filter and the user manager bean are registered when I deploy the application to Glassfish. 当我将应用程序部署到Glassfish时,都会注册过滤器和用户管理器bean。 I wonder what am I doing wrong. 我想知道我做错了什么。 Is there a way to inject a spring managed bean into a ContainerRequestFilter? 有没有办法将spring托管bean注入ContainerRequestFilter?

UPDATE UPDATE

Kind of solved. 有点解决了。 The issue is that Jersey does not obtain Spring beans if these beans are Java proxies (opposed to generated proxy classes). 问题是如果这些bean是Java代理(与生成的代理类相对),Jersey不会获得Spring bean。 The problem can be solved by instructing Spring to ALWAYS use proxy classes instead of Java Proxies by specifying the proxy-target-class="true" attribute in the respective parts of a spring configuration. 通过在spring配置的各个部分中指定proxy-target-class="true"属性,指示Spring始终使用代理类而不是Java代理,可以解决该问题。 In my scenario I had to specify it on a <tx:annotation-driven proxy-target-class="true" /> . 在我的场景中,我必须在<tx:annotation-driven proxy-target-class="true" />上指定它。

See here for a more detailed analysis and a possible fix on that. 请参阅此处以获取更详细的分析以及可能的解决方法。

I'm seeing the same thing with Jersey 1.6 and Spring 3.0.5. 我对Jersey 1.6和Spring 3.0.5也有同样的看法。 Using the debugger, I can tell that even though my code is marked with @Component, both Spring and Jersey will instantiate their own copy of of this class: 使用调试器,我可以说,即使我的代码用@Component标记,Spring和Jersey都会实例化它们自己的这个类的副本:

@Path("/beams")
@Produces("text/xml")
@Component
@Scope("singleton")
public class BeamsResource {
}

There's some chatter that this will be added in a future version of Jersey, but it doesn't seem to be working now. 有一些喋喋不休,这将在未来的泽西岛版本中添加,但它现在似乎没有工作。 I know this is a hideous solution, but I'm using a static member variable to hook together Jersey and Spring for the time being. 我知道这是一个可怕的解决方案,但我正在使用一个静态成员变量暂时将Jersey和Spring挂钩。 Bleh. 的Bleh。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM