将Spring @Resource注入Servlet

时间:2013-08-05 14:31:13

标签: java spring tomcat dependency-injection annotations

我有以下代码,我在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,这会导致异常,

SEVERE: Allocate exception for servlet Deploy Servlet
javax.naming.NameNotFoundException: Name com.example.DeployerServlet is not bound in this Context

那么,将Spring bean注入servlet的推荐方法是什么?

2 个答案:

答案 0 :(得分:1)

@Resource注释是JavaEE element。它用于声明对资源的引用。虽然Spring可以像使用@Inject@Autowired一样使用它,但在这种情况下,servlet Container首先起作用。只需将@Resource替换为@Autowired

答案 1 :(得分:0)

似乎你的构建没有正确完成。清理您的项目并重建。您的问题将解决

相关问题