ApplicationContext中getBean詳解


在org.springframework.context包中有一個接口叫 applicationContext

applicationContext中有一個getBean方法,此方法繼承之BeanFactory

Methods inherited from interface org.springframework.beans.factory.BeanFactory

containsBean, getAliases, getBean, getBean, getBean, getType, isPrototype, isSingleton, isTypeMatch

在BeanFactory中getBean描述如下

 Object getBean(String name)
          Return an instance, which may be shared or independent, of the specified bean.

返回一個指定bean的實例,它可以是共享的、也可以是獨立的。 返回的是對象

Method Detail

Object getBean(String name)throws BeansException
Return an instance, which may be shared or independent, of the specified bean.

This method allows a Spring BeanFactory to be used as a replacement for the Singleton or Prototype design pattern. Callers may retain references to returned objects in the case of Singleton beans.

Translates aliases back to the corresponding canonical bean name. Will ask the parent factory if the bean cannot be found in this factory instance. 

Parameters:
name - the name of the bean to retrieve
Returns:
an instance of the bean
Throws:
NoSuchBeanDefinitionException - if there is no bean definition with the specified name
BeansException - if the bean could not be obtained
實例:

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

UserService service = (UserService)ctx.getBean("userService");

因為getBean返回一個對象,所以要強制轉換

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM