【问题标题】:How to inject spring bean into ContainerRequestFilter using AutoWired?如何使用 AutoWired 将 spring bean 注入 ContainerRequestFilter?
【发布时间】:2018-07-03 11:15:41
【问题描述】:

我正在使用RESTEasy 3Spring 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;
    }

}

有什么方法可以实现吗?真的可以吗?

【问题讨论】:

  • @SumeshTG 这不是方法而是构造函数
  • @Autowired private MyAccessService accessService;试试这个。
  • @SumeshTG 相同的空指针错误
  • 你的组件扫描配置是否正确?
  • @SumeshTG 是的其他依赖项.. 我会尝试检查这个包

标签: java spring filter resteasy


【解决方案1】:

您需要使用WebApplicationContextUtils 的方法来获取一个不受spring 管理的过滤器内的bean。这是一个例子

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

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

  @Context
  private HttpServletRequest httpServletRequest ;

【讨论】:

    【解决方案2】:

    看起来您将@Autowired 注释放置在错误的位置。它应该在 accessService 的声明之上。并且根据您配置应用程序上下文的方式,您可能/可能不需要 accessService 实例变量的 setter 方法。

    【讨论】:

      猜你喜欢
      • 2019-08-11
      • 2021-04-24
      • 2013-06-25
      • 2011-04-14
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-05
      相关资源
      最近更新 更多