您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

我想使用Spring在Servlet中注入对象

我想使用Spring在Servlet中注入对象

您正在混淆两个概念: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" class="mypackage.servletOne">
        <property name="message" ref="classObject" />
</bean>

就像我在这里的答案一样,因为ContextLoaderListenerApplicationContext它创建的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

Jave 2022/1/1 18:14:58 有533人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶