Java 如何使用AutoWired将Springbean注入ContainerRequestFilter?
我正在使用Java 如何使用AutoWired将Springbean注入ContainerRequestFilter?,java,spring,filter,resteasy,Java,Spring,Filter,Resteasy,我正在使用RESTEasy 3和Spring 4,并尝试将@Autowired服务bean注入我的拦截器,如下所示: 但在访问我的访问服务时,运行此代码将返回空指针异常: @Provider @MyAnnotationToIntercept public class MyInterceptor implements ContainerRequestFilter { private MyAccessService accessService; @Autowired p
RESTEasy 3
和Spring 4
,并尝试将@Autowired
服务bean注入我的拦截器,如下所示:
但在访问我的访问服务时,运行此代码将返回空指针异常
:
@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,而这个bean不是由spring管理的。这是一个例子
MyAccessService myAccessService = (MyAccessService) WebApplicationContextUtils.getRequiredWebApplicationContext(httpServletRequest .getServletContext()).getBean(MyAccessService.class);
要获取HttpServletRequest
实例,可以使用@context
注入
@Context
private HttpServletRequest httpServletRequest ;
您将需要使用
WebApplicationContextUtils
的方法来获取一个不由spring管理的过滤器内部的bean。这是一个例子
MyAccessService myAccessService = (MyAccessService) WebApplicationContextUtils.getRequiredWebApplicationContext(httpServletRequest .getServletContext()).getBean(MyAccessService.class);
要获取HttpServletRequest
实例,可以使用@context
注入
@Context
private HttpServletRequest httpServletRequest ;
看起来您在错误的位置放置了@Autowired注释。它应该位于accessService声明之上。根据您配置应用程序上下文的方式,您可能/可能不需要accessService实例变量的setter方法 看起来您将@Autowired注释放置在了错误的位置。它应该位于accessService声明之上。根据您配置应用程序上下文的方式,您可能/可能不需要accessService实例变量的setter方法 @SumeshTG这不是一种方法,而是一种方法Constructor@Autowired私有MyAccessService;尝试此操作。@SumeshTG相同的空指针错误您的组件扫描配置是否正确?@SumeshTG其他依赖项为“是”。。我会试着检查一下package@SumeshTG这不是一种方法,而是一种方法Constructor@Autowired私有MyAccessService;尝试此操作。@SumeshTG相同的空指针错误您的组件扫描配置是否正确?@SumeshTG其他依赖项为“是”。。我会试着检查一下这个包裹