2013-08-05 28 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