簡體   English   中英

如何使用AutoWired將Spring bean注入ContainerRequestFilter?

[英]How to inject spring bean into ContainerRequestFilter using AutoWired?

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

}

有什么辦法可以做到這一點? 真的有可能嗎?

您將需要使用WebApplicationContextUtils的方法來獲取過濾器內部的bean,該過濾器不受spring的管理。 這是例子

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

為了獲得HttpServletRequest實例,您可以使用@context注入

  @Context
  private HttpServletRequest httpServletRequest ;

好像您將@Autowired注釋放置在錯誤的位置。 它應該在accessService的聲明之上。 並且取決於您如何配置應用程序上下文,您可能會/可能不需要accessService實例變量的setter方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM