2009-01-21 68 views
24

我想在JBoss中編寫一個簡單的servlet,它將調用Spring bean上的方法。其目的是允許用戶通過點擊URL來啓動內部作業。從JBoss中的servlet訪問Spring beans

在servlet中獲取Spring bean引用的最簡單方法是什麼?

JBoss Web服務允許您使用@Resource註釋將WebServiceContext注入服務類。在純servlet中有什麼可比的嗎?解決這個特定問題的網絡服務將使用大錘壓碎堅果。

回答

31

servlet可以使用WebApplicationContextUtils獲得應用程序上下文,但隨後你的servlet代碼對Spring框架的直接依賴。

另一種解決方案是配置應用程序上下文中的Spring bean作爲屬性導出到servlet上下文:

<bean class="org.springframework.web.context.support.ServletContextAttributeExporter"> 
    <property name="attributes"> 
    <map> 
     <entry key="jobbie" value-ref="springifiedJobbie"/> 
    </map> 
    </property> 
</bean> 

servlet可以使用

SpringifiedJobbie jobbie = (SpringifiedJobbie) getServletContext().getAttribute("jobbie"); 
+0

不錯,謝謝。 – 2009-01-22 01:44:13

+0

這樣做並且不使用WebApplicationContextUtils有什麼好處?無論哪種方式,它都與Spring有關。 – Elliot 2009-12-29 19:51:20

7

我發現做這件事:

WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); 
SpringifiedJobbie jobbie = (SpringifiedJobbie)context.getBean("springifiedJobbie"); 
58

有檢索servlet上下文豆是一個更加複雜的方法來做到這一點。有SpringBeanAutowiringSupportorg.springframework.web.context.support,允許你建立這樣的事情:

public class MyServlet extends HttpServlet { 

    @Autowired 
    private MyService myService; 

    public void init(ServletConfig config) { 
    super.init(config); 
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, 
     config.getServletContext()); 
    } 
} 

這將導致春天來查找ApplicationContext綁到ServletContext(例如,通過ContextLoaderListener創建),並注入該ApplicationContext可用的Spring bean。