首页 > 解决方案 > 如何使用 AutoWired 将 spring bean 注入 ContainerRequestFilter?

问题描述

我正在使用RESTEasy 3并且Spring 4我正在尝试将@Autowired服务 bean 注入我的拦截器,如下所示:

但是运行此代码时,它会Null Pointer Exception在访问我的访问服务时返回:

@Provider
@MyAnnotationToIntercept
public class MyInterceptor implements ContainerRequestFilter {


    private MyAccessService accessService;

    @Autowired
    public MyInterceptor(MyAccessService accessService) {
        this.accessService = accessService;
    }

    public MyInterceptor() {
    }

    @Override
    public void filter(ContainerRequestContext requestContext) {

        // DO SOME STUFF Using accessService
    }
}


@Component
public class MyAccessService {

    private MyDep1 dep1;

    @Autowired
    public MyAccessService(Mydep1 dep1) {
        this.dep1= dep1;
    }

}

有什么办法可以做到这一点?真的有可能吗?

标签: javaspringfilterresteasy

解决方案


您将需要使用WebApplicationContextUtils' 方法在过滤器中获取一个不受 spring 管理的 bean。这是示例

MyAccessService myAccessService = (MyAccessService) WebApplicationContextUtils.getRequiredWebApplicationContext(httpServletRequest .getServletContext()).getBean(MyAccessService.class);

要获取HttpServletRequest实例,您可以使用@context注入

  @Context
  private HttpServletRequest httpServletRequest ;

推荐阅读