2013-08-05 22 views
1

我有下面一段代码,这是我对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推荐的方法是什么?

+0

这取决于。你介意你的servlet中的spring classes有依赖吗? – mael

+0

我对servlet中的'SpringBeanAutowiringSupport'已经很好了,所以我觉得没问题。但是,使用声明性的'@ Resource'而不是直接的'applicationContext.getBean()'调用会很好。 – Saintali

+1

因为Container负责初始化Servlet,所以你不得不使用'SpringBeanAutowiringSupport'来实现你想要的。 Servlet不是由Spring管理的。 –

回答

1

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

+0

请注意'@ Autowired'和'@ Resource'之间略有不同:后者先按名称绑定Bean,然后回退到按类型绑定;前者仅按类型绑定,仅使用名称(由“@ Qualifier”注释提供)作为提示(http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch04s11。 HTML)。 – Jerzyna

0

似乎是你的构建没有做好。清理你的项目并重建。您的问题将解决

+0

我使用Maven,并且一直在多个构建中获取此错误。另外我不明白这可能是一个构建问题,因为显然没有这样的JNDI名称。 – Saintali