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描述如下

 ObjectgetBean(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返回一个对象,所以要强制转换

 

转载于:https://www.cnblogs.com/batman425/p/7475730.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值