我有下面一段代码,这是我对this answer建模:将Spring @Resource成servlet
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的尝试查找名称com.example.DeployerServlet/engine
在JNDI导致的异常,
SEVERE: Allocate exception for servlet Deploy Servlet
javax.naming.NameNotFoundException: Name com.example.DeployerServlet is not bound in this Context
那么,什么是注入一个Spring bean成servlet推荐的方法是什么?
这取决于。你介意你的servlet中的spring classes有依赖吗? – mael
我对servlet中的'SpringBeanAutowiringSupport'已经很好了,所以我觉得没问题。但是,使用声明性的'@ Resource'而不是直接的'applicationContext.getBean()'调用会很好。 – Saintali
因为Container负责初始化Servlet,所以你不得不使用'SpringBeanAutowiringSupport'来实现你想要的。 Servlet不是由Spring管理的。 –