BeanFactory與FactoryBean1

BeanFactory爲一個管理bean的工廠(即爲spring的容器),它管理的對象可以是bean也可以是FactoryBean(這種請況會再調用FactoryBeangetObject()獲取真正的bean)

FactoryBean爲一個工廠bean,受BeanFactory管理。

 

先來看一看BeanFactory

public interface BeanFactory {

String FACTORY_BEAN_PREFIX = "&";

Object getBean(String name);

Object getBean(String name, Class requiredType);

boolean containsBean(String name);

boolean isSingleton(String name);

boolean isPrototype(String name);

boolean isTypeMatch(String name, Class targetType);

Class getType(String name);

String[] getAliases(String name);

}

 

BeanFactory調用者只需要調用getBean方法即可獲得指定bean的引用。

 

 
ApplicationContext繼承自BeanFactory,它擁有BeanFactory提供的所有配置框架和基本的功能, 而且 ApplicationContext爲它增加了更強的功能。因此通常在J2EE環境的應用中,最好選擇使用ApplicationContext下的子類。

 

Web應用通過在web.xml中的配置(具體參見:web應用中自動加載ApplicationContext http://java999.blog.51cto.com/259217/196397),啓動時會自動加載ApplicationContext實例。在web應用中雖然幾乎所有被BeanFactory管理的用戶代碼都不需要知道BeanFactory 但是在內部實現中,BeanFactory還是以某種方式實例化。對於獨立的引用程序或者一些Servletactionjsp可以使用以下的方法實例化BeanFactory

    Resource resource = new FileSystemResource("beans.xml");

    BeanFactory factory = new XmlBeanFactory(resource);

 

    ClassPathResource resource = new ClassPathResource("beans.xml");

    BeanFactory factory = new XmlBeanFactory(resource);

 

    ApplicationContext context = new ClassPathXmlApplicationContext(

new String[] {"applicationContext.xml", "applicationContext-part2.xml"});

    BeanFactory factory = (BeanFactory) context;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章