afrag |
|
|||
記錄學(xué)習(xí)和成長(zhǎng)的歷程 |
日歷
統(tǒng)計(jì)
導(dǎo)航常用鏈接留言簿隨筆分類隨筆檔案文章檔案搜索積分與排名
最新評(píng)論
閱讀排行榜評(píng)論排行榜 |
ApplicationContext比BeanFactory提供了更多的功能,因此一般情況下都會(huì)使用ApplicationContext,只有在資源有限的情況下(例如在移動(dòng)設(shè)備上)才使用BeanFactory。 在ApplicationContext的多個(gè)實(shí)現(xiàn)中,最常用的有3個(gè): ClassPathXmlApplicationContext:在所有的classpath中查找指定的xml文件。 FileSystemXmlApplicationContext:在文件系統(tǒng)中查找指定的xml文件。(可以指定相對(duì)路徑,當(dāng)前路徑為當(dāng)前目錄)。 XmlWebApplicationContext:從一個(gè)web應(yīng)用程序中包含的xml文件中讀取context定義。 ApplicationContext是擴(kuò)展的BeanFactory接口 public interface ApplicationContext extends ListableBeanFactory, HierarchicalBeanFactory, MessageSource, ApplicationEventPublisher, ResourcePatternResolver{ ………… } 從ApplicationContext獲取對(duì)象也是使用getBean方法。 ApplicationContext和BeanFactory有一個(gè)很大的不同是:BeanFactory是在需要bean的時(shí)候才會(huì)實(shí)例化bean;ApplicationContext會(huì)在裝入context的時(shí)候預(yù)先裝入所有的singleton的bean。(singleton是在bean的定義中<bean>元素的一個(gè)屬性,缺省值為true)。 例如,針對(duì)上一節(jié)的例子,我們將ExecutableApp類更改為: import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.FileSystemResource; public class ExecutableApp { public ExecutableApp () { } public static void main(String args[]){ System.out.println(“Before load xml file”); ApplicationContext factory= new FileSystemXmlApplicationContext("configuration.xml"); System.out.println(“After load xml file”); Greeting personA = (Greeting)factory.getBean("greetingService"); personA.sayHello(); } } 運(yùn)行的結(jié)果是: Instance GreetingImpl object Instance MrSmith object After load xml file Hi,Mr Smith 也就是說,ApplicationContext在裝載xml文件的同時(shí)就實(shí)例化了GreetingImpl類和MrSmith類。 如果我們將xml文件的更改為: <!DOCTYPE beans PUBLIC "-//SPRING//DTDBEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="person" class="MrSmith" singleton="false"/> <bean id="greetingService" class="GreetingImpl" singleton="false"> <property name="greeting"> <value>Hello</value> </property> <property name="who”> <ref bean="person"/> </property> </bean> </beans> Before load xml file
|
![]() |
|
Copyright © afrag | Powered by: 博客園 模板提供:滬江博客 |