Injecting Spring @Resource into a Servlet

2019-07-26 14:03发布

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. 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

So, what is the recommended way to inject a Spring bean into a servlet?

2条回答
放荡不羁爱自由
2楼-- · 2019-07-26 14:23

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.

查看更多
劳资没心,怎么记你
3楼-- · 2019-07-26 14:30

Seems to be your build is not properly done. clean your project and rebuild. Your issue will solve

查看更多
登录 后发表回答