将 Spring @Resource 注入 Servlet [英] Injecting Spring @Resource into a Servlet
问题描述
我有以下一段代码,我以这个答案为模型:
I have the following piece of code, which I modeled on this answer:
public class DeployerServlet extends HttpServlet {
@Resource
Engine engine;
public void init(ServletConfig config) throws ServletException {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
}
// ...
}
但是 servlet 甚至没有正确实例化.在创建实例时,Tomcat 尝试在 JNDI 中查找名称 com.example.DeployerServlet/engine
这导致异常,
But the servlet is not even correctly instantiated. When creating an instance, Tomcat tries to look up the name com.example.DeployerServlet/engine
in JNDI which results in an exception,
SEVERE: Allocate exception for servlet Deploy Servlet
javax.naming.NameNotFoundException: Name com.example.DeployerServlet is not bound in this Context
那么,将 Spring bean 注入 servlet 的推荐方法是什么?
So, what is the recommended way to inject a Spring bean into a servlet?
推荐答案
@Resource
注释是一个 JavaEE 元素.它用于声明对资源的引用.尽管 Spring 可以像使用 @Inject
和 @Autowired
一样使用它,但在这种情况下,servlet 容器首先起作用.只需将您的 @Resource
替换为 @Autowired
.
The @Resource
annotation is a JavaEE element. It's used to declare a reference to a resource. Although Spring can use it the same way it does with @Inject
and @Autowired
, in this case the servlet Container acts first. Just replace your @Resource
with @Autowired
.
这篇关于将 Spring @Resource 注入 Servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!