ApplicationContext比BeanFactory提供了更多的功能,因此一般情況下都會使用ApplicationContext,只有在資源有限的情況下(例如在移動設備上)才使用BeanFactory。
在ApplicationContext的多個實現中,最常用的有3個:
ClassPathXmlApplicationContext:在所有的classpath中查找指定的xml文件。
FileSystemXmlApplicationContext:在文件系統中查找指定的xml文件。(可以指定相對路徑,當前路徑為當前目錄)。
XmlWebApplicationContext:從一個web應用程序中包含的xml文件中讀取context定義。
ApplicationContext是擴展的BeanFactory接口
public interface ApplicationContext extends ListableBeanFactory, HierarchicalBeanFactory,
MessageSource, ApplicationEventPublisher, ResourcePatternResolver{
…………
}
從ApplicationContext獲取對象也是使用getBean方法。
ApplicationContext和BeanFactory有一個很大的不同是:BeanFactory是在需要bean的時候才會實例化bean;ApplicationContext會在裝入context的時候預先裝入所有的singleton的bean。(singleton是在bean的定義中<bean>元素的一個屬性,缺省值為true)。
例如,針對上一節的例子,我們將ExecutableApp類更改為:
import org.springframework.beans.factory.BeanFactory;
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();
}
}
運行的結果是:
Before load xml file
Instance GreetingImpl object
Instance MrSmith object
After load xml file
Hi,Mr Smith
也就是說,ApplicationContext在裝載xml文件的同時就實例化了GreetingImpl類和MrSmith類。
如果我們將xml文件的更改為:
<?xml version = "1.0" encoding="UTF-8"?>
<!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>
那么ExecutableApp的運行結果是:
Before load xml file
After load xml file
Instance GreetingImpl object
Instance MrSmith object
Hi,Mr Smith
也就是說,在裝載xml文件時,ApplicationContext并沒有實例化GreetingImpl類和MrSmith類,直到需要這兩個類的時候才會實例化它們。