简体   繁体   English

将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());
    }

    // ...
}

But the servlet is not even correctly instantiated. 但是,servlet甚至没有正确实例化。 When creating an instance, Tomcat tries to look up the name com.example.DeployerServlet/engine in JNDI which results in an exception, 创建实例时,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

So, what is the recommended way to inject a Spring bean into a servlet? 那么,将Spring bean注入servlet的推荐方法是什么?

The @Resource annotation is a JavaEE element . @Resource批注是一个JavaEE元素 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. 尽管Spring可以像使用@Inject@Autowired一样使用它,但是在这种情况下,servlet容器首先起作用。 Just replace your @Resource with @Autowired . 只需将@Resource替换为@Autowired

Seems to be your build is not properly done. 似乎是您的构建未正确完成。 clean your project and rebuild. 清理您的项目并重建。 Your issue will solve 您的问题会解决

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM