您正在混淆两个概念:Servlet和Spring的ApplicationContext
。Servlet由Servlet容器管理,以Tomcat为例。在ApplicationContext
由Spring管理。
Servlet
在部署描述符中将a声明为
<servlet>
<servlet-name>servletOne</servlet-name>
<servlet-class>mypackage.servletOne</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletOne</servlet-name>
<url-pattern>/servletOne</url-pattern>
</servlet-mapping>
Servlet容器将创建您的mypackage.servletOne
类的实例,进行注册,并使用它来处理请求。这就是DispatcherServlet
Spring MVC的基础。
Spring是一个IoC容器,用于ApplicationContext
管理许多bean。该ContextLoaderListener
负载根ApplicationContext
(无论从任何位置,你告诉它)。在DispatcherServlet
使用了根上下文,因此也必须加载其自身。上下文必须具有适当的配置DispatcherServlet
才能工作。
在Spring上下文中声明一个bean,例如
<bean id="servletFirst" class="mypackage.servletOne">
<property name="message" ref="classObject" />
</bean>
就像我在这里的答案一样,因为ContextLoaderListener
将ApplicationContext
它创建的putsServletContext
作为属性,所以ApplicationContext
任何Servlet容器托管对象都可以使用它。因此,您可以像这样HttpServlet#init(ServletConfig)
在自定义HttpServlet
类中覆盖
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ApplicationContext ac = (ApplicationContext) config.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
this.someObject = (SomeBean)ac.getBean("someBeanRef");
}
假设您的根ApplicationContext
包含一个名为的bean someBeanRef
。