从JBoss中的servlet访问Spring bean

Sop*_*age 24 java jboss spring servlets java-ee

我想在JBoss中编写一个简单的servlet,它将在Spring bean上调用一个方法.目的是允许用户通过点击URL来启动内部作业.

在servlet中获取对Spring bean的引用的最简单方法是什么?

JBoss Web服务允许您使用@Resource注释将WebServiceContext注入服务类.有没有类似的可用于普通的servlet?解决这一特殊问题的网络服务将使用大锤来粉碎坚果.

Oli*_*ohm 60

有一种更复杂的方法可以做到这一点.有SpringBeanAutowiringSupport内部的org.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());
  }
}
Run Code Online (Sandbox Code Playgroud)

这将导致Spring查找ApplicationContext绑定到那个ServletContext(例如创建的via ContextLoaderListener)并注入可用的Spring bean ApplicationContext.

  • 在Spring 2.5.x中它应该是SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); 自动处理其余的.很棒的提示顺便说一句. (4认同)

Chi*_*ang 31

您的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>
Run Code Online (Sandbox Code Playgroud)

您的servlet可以使用从servlet上下文中检索bean

SpringifiedJobbie jobbie = (SpringifiedJobbie) getServletContext().getAttribute("jobbie");
Run Code Online (Sandbox Code Playgroud)

  • 填充servlet上下文属性的机制不必使用Spring实现.在启动时运行的过滤器或另一个servlet可以填充servlet上下文属性. (5认同)

Sop*_*age 8

我找到了一种方法:

WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
SpringifiedJobbie jobbie = (SpringifiedJobbie)context.getBean("springifiedJobbie");
Run Code Online (Sandbox Code Playgroud)