您正在混淆两个概念: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类的实例,进行注册,并使用它来处理请求。这就是
DispatcherServletSpring
MVC的基础。
Spring是一个IoC容器,用于
ApplicationContext管理许多bean。该
ContextLoaderListener负载根
ApplicationContext(无论从任何位置,你告诉它)。在
DispatcherServlet使用了根上下文,因此也必须加载其自身。上下文必须具有适当的配置
DispatcherServlet才能工作。
在Spring上下文中声明一个bean,例如
<bean id="servletFirst" > <property name="message" ref="classObject" /></bean>
不管它与<servlet>
web.xml中声明的类型是否相同,都是完全无关的。上面的bean与<servlet>
web.xml中的声明无关。
就像我在这里的答案一样,因为
ContextLoaderListener将
ApplicationContext它创建的puts
ServletContext作为属性,所以
ApplicationContext任何Servlet容器托管对象都可以使用它。因此,您可以像这样
HttpServlet#init(ServletConfig)在自定义
HttpServlet类中覆盖
@Overridepublic 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。



