簡體   English   中英

從JBoss中的servlet訪問Spring bean

[英]Access Spring beans from a servlet in JBoss

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

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

JBoss Web服務允許您使用@Resource注釋將WebServiceContext注入服務類。 有沒有類似的可用於普通的servlet? 解決這一特殊問題的網絡服務將使用大錘來粉碎堅果。

有一種更復雜的方法可以做到這一點。 org.springframework.web.context.support中有SpringBeanAutowiringSupport ,它允許你構建這樣的東西:

public class MyServlet extends HttpServlet {

  @Autowired
  private MyService myService;

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

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

您的servlet可以使用WebApplicationContextUtils來獲取應用程序上下文,但是您的servlet代碼將直接依賴於Spring Framework。

另一個解決方案是配置應用程序上下文以將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可以使用從servlet上下文中檢索bean

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

我找到了一種方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM