ClassPathxmlapplicationContext:類路徑加載 FileSystemXmlApplicationContext:文件系統(tǒng)路徑加載 AnnotationConfigApplicationContext:用于基于注解的配置 WebApplicationContext:專門為web應(yīng)用準(zhǔn)備的,從相對于Web根目錄的路徑中裝載配置文件完成初始化。
ApplicationContext ac = new ClassPathXmlApplicationContext("com/zzm/context/beans.xml");//等同路徑:"classpath:com/zzm/context/beans.xml"ac.getBean("abc",abc.calss);//就可以獲得bean了ApplicationContext ac = new FileSystemXmlApplicationContext("com/zzm/context/beans.xml");//等同路徑:"file:com/zzm/context/beans.xml"ac.getBean("abc",abc.calss);//就可以獲得bean了加載多個配置文件:
ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"conf/beans1.xml","conf.beans2.xml"});對于基于注解的,如:
@Conigurationpublic class Beans{ @Bean(name="man") public Man newMan(){ Man man = new Man(); man.setName("小明"); }}用
ApplicationContext ac = new AnnotationConfigApplicationContext(Beans.class);Man man = ac.getBean("man",Man.class);WebApplicationContext初始化需要ServletContext事例,即必須先有Web容器才能完成啟動工作,可在web.xml中配置自啟動Servlet或定義Web容器監(jiān)聽器(ServletContextListener)。
通過Web容器監(jiān)聽器:
web.xml:<!--指定配置文件--><context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/zzm-service.xml</param-value> <!--也可以類路徑:classpath:com/zzm/service.xml 可指定多個用,隔開--></context-param><!--聲明Web容器監(jiān)聽--><listener> <listener-class>org.sPRingframework.web.context.ContextLoaderListener</listener-class></listener>通過自啟動的Servlet引導(dǎo)
<!--指定配置文件--><context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/zzm-service.xml</param-value></context-param><!--聲明自啟動的Servlet容器><servlet> <servlet-name>sprinfContextLoaderServlet</servlet-name> <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> <load-on-startup>1</load-on-startup></servlet>WebApplicationContext Spring提供WebApplicationContextUtils通過該類的getWebApplicationContext(ServletContext sc)方法獲取,即可從ServletContext中獲取WebApplicationContext。 新增3作用域:request,session,global session 像Spring中用過濾器Filter,如過濾器中需要加載配置時可用WebApplicationContext來加載
public class ACLFilter implements Filter{private ServletContext sc;private ApplicationContext ctx;private UserService userService;/** * 過濾器初始化 */public void init(FilterConfig cfg) throws ServletException { sc= cfg.getServletContext();//獲取Spring容器 ctx=WebApplicationContextUtils.getWebApplicationContext(sc);//從容器中獲取 UserService 對象 userService=ctx.getBean("userService",UserService.class);}public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain)throws IOException, ServletException { /**/ chain.doFilter(request, response); }public void destroy() {}}
|
新聞熱點
疑難解答