如何在web.xml中将HttpServlet与Spring Application Context连接? [英] How to connect HttpServlet with Spring Application Context in web.xml?

查看:90
本文介绍了如何在web.xml中将HttpServlet与Spring Application Context连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将扩展HttpServlet的FooServlet与同一项目中的ApplicationContext连接起来. Wicket Servlet已经使用了Application Context

I'm trying to connect my FooServlet which extends HttpServlet with the ApplicationContext which is in the same Project. The Application Context is already used by a Wicket Servlet

它与

servletContext = this.getServletContext();
wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
(IMyBean)wac().getBean("myServiceBean")

现在,我尝试避免在我的代码(WebApplicationContextUtils)中明确使用Spring类,因为这不是IoC方式.

Now I try to aviod to use explicitly Spring Classes in my Code (WebApplicationContextUtils) as it's not the IoC way.

Wicket Servlet在web.xml中与Application上下文连接

The Wicket Servlet is connected with the Application context in the web.xml

<servlet>
  <servlet-name>ExampleApplication</servlet-name>
  <servlet-class>org.apache.wicket.protocol.http.WicketServlet</servlet-class>
    <init-param>
      <param-name>applicationFactoryClassName</param-name>
      <param-value>org.apache.wicket.spring.SpringWebApplicationFactory</param-value>
    </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>

我找到了Spring HttpServletBean类,但是我不知道它是否适用于我的Case

I found the class Spring HttpServletBean but I don't know if it serves for my Case

推荐答案

我找到了一种在HttpServlet中注入Bean的方法(注意:我不需要Presentation View,否则还有更多高级春季课程)

I found a way to inject Beans in my HttpServlet (Note: I don't need a Presentation View, otherwise there are more advanced Spring Classes)

在web.xml中添加一个ContextLoaderListener,以便加载Spring的根WebApplicationContext

Add a ContextLoaderListener to web.xml so that Spring's root WebApplicationContext is loaded

   <listener>
      <listener-class>
        org.springframework.web.context.ContextLoaderListener
      </listener-class>
   </listener>

使用Springs配置Servlet

Configure Servlet using Springs HttpRequestHandlerServlet Class

<servlet>
 <servlet-name>FooServlet</servlet-name>
 <display-name>Foo Servlet</display-name>
 <servlet-class>
      org.springframework.web.context.support.HttpRequestHandlerServlet
    </servlet-class>
</servlet>

让您的Servlet实现

Let your Servlet implement the org.springframework.web.HttpRequestHandler Interface

在ApplicationContext中将Servlet定义为Bean(beanID必须与"servlet-name"相同). 现在可以通过Spring DependencyInjection方式注入所有必需的Bean,而无需进行依赖关系查找.

Define your Servlet as a Bean in ApplicationContext (beanID must be same as "servlet-name"). Now it's possible to inject all necassary Beans in the Spring DependencyInjection way without dependency lookup.

这篇关于如何在web.xml中将HttpServlet与Spring Application Context连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆