幾個applicationcontext實現類

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"});

對於基於註解的,如:

@Coniguration
public 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() {
}

}

發佈了23 篇原創文章 · 獲贊 20 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章