spring-9-在 web 项目中获取 Application

2020-06-22  本文已影响0人  blank_white

在 web.xml 中添加如下
使用 spring 提供的 listener
此 listener 会在服务器启动时,注册 ApplicationContext 对象放在 servletContext 中

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

// 使用工具类 从 servletContext 中拿到  ctx
WebApplicationContext ctx= WebApplicationContextUtils.getWebApplicationContext(getServletContext());
StudentService studentService= (StudentService) ctx.getBean("studentService");
//org.springframework.web.context.WebApplicationContext;
// 可见此类 是继承了  ApplicationContext ,用于在 Web 项目
public interface WebApplicationContext extends ApplicationContext {
上一篇 下一篇

猜你喜欢

热点阅读