当前位置: 代码迷 >> Web前端 >> Web项目器皿启动就初始化Spring容器的方式
  详细解决方案

Web项目器皿启动就初始化Spring容器的方式

热度:122   发布时间:2013-08-14 14:27:55.0
Web项目容器启动就初始化Spring容器的方式。
初始化方式一:

servlet中init方法中完成。但是init方法在第一次访问的时候才执行。


@Override

public void init() throws ServletException {


System.out.println("Servlet初始化,并且初始化Spring");

//通过spring容器获取一个bean对象

//第一步初始化spring容器(工厂)

applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");


//把spring放到web的application对象中。

getServletContext().setAttribute("applicationContext",applicationContext);


//其他的servlet中.

getServletContext().getAttribute("applicationContext");

}

?

  初始化方式二:
  通过web listeners
  ServletContextListener ->容器启动过程中调用该监听器。
  
  [  web.xml  ]
  	  <!--
    	 配置spring初始化容器的监听器
    	  监听器:创建applicationContext对象并且放到servletContext中.
    -->
    <listener>
    	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    
    <!--
    	 配置spring的配置文件路径,如果不写默认使用WEB-INF/applicationContext.xml 
    -->
    <context-param>
    	 <param-name>contextConfigLocation</param-name>
    	 <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
        
      代码中使用:
      AppliationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
      context.getBean(beanId);

??

?

?

  相关解决方案