java - 如何使用 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;
}
}
有什么办法可以做到这一点?真的有可能吗?
解决方案
您将需要使用WebApplicationContextUtils
' 方法在过滤器中获取一个不受 spring 管理的 bean。这是示例
MyAccessService myAccessService = (MyAccessService) WebApplicationContextUtils.getRequiredWebApplicationContext(httpServletRequest .getServletContext()).getBean(MyAccessService.class);
要获取HttpServletRequest
实例,您可以使用@context
注入
@Context
private HttpServletRequest httpServletRequest ;
推荐阅读
- python - 去除音频频谱图中的水平线
- google-apps-script - 谷歌表单,保护信息
- python - 方便的索引:在 Python 的字典中存储指向列表的指针?
- angular - Angular 7与iframe链接
- hibernate - SpringBoot 亲子关系
- mysql - 如何从同一个表的两列中选择 DISTINCT 行而忽略双向相似性?
- lotus-notes - IBM Notes 仅允许在某些计算机上创建检查记录
- node.js - 未收到来自 SendGrid 的电子邮件
- php - PHP数组未定义索引注意事项
- palindrome - 我的 HTML 和 JS 回文脚本有什么问题或缺少什么?