Java技术专题

监听器获取spring配置文件创建的对象

2018-10-07  本文已影响32人  爱撒谎的男孩

监听器获取spring配置文件创建的对象

前提

准备

<!--配置spring配置问文件的路径-->
<context-param>
        <param-name>contextConfigLocation</param-name>
        <!--使用通配符指定多个配置文件,比如 spring-service.xml,spring-dao.xml-->
        <param-value>classpath:spring-*.xml</param-value>
    </context-param>
    <!--spring监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

实现

public class InitCompontServletContextListener implements ServletContextListener, ServletContextAttributeListener {
    
    private BlogIndex blogIndex;    //spring配置创建的对象
    private IBlogService blogService;   //spring配置创建的对象

    /**
     * web容器初始化的时候就会调用
     */
    public void contextInitialized(ServletContextEvent contextEvent)  {
        ServletContext context=contextEvent.getServletContext();  //获取上下文对象
        WebApplicationContext applicationContext=WebApplicationContextUtils.getRequiredWebApplicationContext(context);
        blogIndex=applicationContext.getBean("blogIndex",BlogIndex.class);  //加载BlogIndex对象
        blogService=applicationContext.getBean("blogServiceImpl",IBlogService.class);  //加载IBlogService对象
    }

参考文章

上一篇 下一篇

猜你喜欢

热点阅读