ClassPathxmlapplicationContext:类路径加载 FileSystemXmlApplicationContext:文件系统路径加载 AnnotationConfigApplicationContext:用于基于注解的配置 WebApplicationContext:专门为web应用准备的,从相对于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容器监听器(ServletContextListener)。
通过Web容器监听器:
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容器监听--><listener> <listener-class>org.sPRingframework.web.context.ContextLoaderListener</listener-class></listener>通过自启动的Servlet引导
<!--指定配置文件--><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() {}}
新闻热点
疑难解答