美文网首页
spring-9-在 web 项目中获取 Application

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

作者: blank_white | 来源:发表于2020-06-22 19:30 被阅读0次

在 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 {

相关文章

网友评论

      本文标题:spring-9-在 web 项目中获取 Application

      本文链接:https://www.haomeiwen.com/subject/simfghtx.html