【问题标题】:Access Spring beans from a servlet in JBoss从 JBoss 中的 servlet 访问 Spring bean
【发布时间】:2009-01-21 22:11:11
【问题描述】:

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

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

JBoss Web 服务允许您使用 @Resource 注释将 WebServiceContext 注入到您的服务类中。有什么类似的东西可以在普通的 servlet 中工作吗?解决此特定问题的 Web 服务将使用大锤来粉碎坚果。

【问题讨论】:

    标签: java spring jakarta-ee servlets jboss


    【解决方案1】:

    有一种更复杂的方法可以做到这一点。 SpringBeanAutowiringSupportinside 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());
      }
    }
    

    这将导致 Spring 查找与该 ServletContext 相关联的 ApplicationContext(例如,通过 ContextLoaderListener 创建)并注入该 ApplicationContext 中可用的 Spring bean。

    【讨论】:

    • 在 Spring 2.5.x 中应该是 SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);它会自动处理其余部分。顺便说一句,很棒的提示。
    • 如果您需要访问任何ServletConfig,请确保在“init”方法中调用“super.init(config)”;例如public void init(ServletConfig config) { super.init(config); SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); }
    • 在 Servlet 中使用实例变量存在已知的数据访问竞争条件风险(如果您不遵循 SingleThreadModel)。我相信如果实例变量是自动装配的,风险仍然存在。 OWASP 链接:owasp.org/index.php/Member_Field_Race_Condition
    【解决方案2】:

    您的 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");
    

    【讨论】:

    • 这样做而不使用 WebApplicationContextUtils 有什么好处?无论哪种方式,它都与 Spring 相关联。
    • 填充 servlet 上下文属性的机制不必使用 Spring 来实现。在启动时运行的过滤器或另一个 servlet 可以填充 servlet 上下文属性。
    【解决方案3】:

    我找到了一种方法:

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

    【讨论】:

      猜你喜欢
      • 2013-06-22
      • 2011-01-25
      • 2017-03-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-27
      • 2014-05-29
      • 2014-10-17
      • 1970-01-01
      相关资源
      最近更新 更多