如何在web.xml中将HttpServlet与Spring Application Context连接?

Mar*_*ier 5 spring

我正在尝试连接我的FooServlet,它扩展了HttpServlet和ApplicationContext,它位于同一个Project中.Wicket Servlet已经使用了应用程序上下文

它适用于

servletContext = this.getServletContext();
wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
(IMyBean)wac().getBean("myServiceBean")
Run Code Online (Sandbox Code Playgroud)

现在我尝试在我的代码(WebApplicationContextUtils)中使用显式Spring类,因为它不是IoC方式.

Wicket Servlet与web.xml中的Application上下文相关联

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

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

Mar*_*ier 15

我找到了一种在我的HttpServlet中注入Beans的方法(注意:我不需要Presentation View,否则有更高级的Spring类)

将ContextLoaderListener添加到web.xml,以便加载Spring的根WebApplicationContext

   <listener>
      <listener-class>
        org.springframework.web.context.ContextLoaderListener
      </listener-class>
   </listener>
Run Code Online (Sandbox Code Playgroud)

使用Springs HttpRequestHandlerServlet类配置Servlet

<servlet>
 <servlet-name>FooServlet</servlet-name>
 <display-name>Foo Servlet</display-name>
 <servlet-class>
      org.springframework.web.context.support.HttpRequestHandlerServlet
    </servlet-class>
</servlet>
Run Code Online (Sandbox Code Playgroud)

让您的Servlet实现org.springframework.web.HttpRequestHandler接口

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