Spring学习笔记之Bean基本管理(BeanFactory,ApplicationContext)

本文详细介绍了Spring框架中BeanFactory接口的功能及其实现方法,并对比了ApplicationContext的优势,提供了实际的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring2中:

BeanFactory接口定义了6种方法:

 Object getBean(String)

Object getBean(String,Class) 取得相对应的Bean实例,并转换Cast至指定的类.

boolean containsBean(String) 测试BeanFactory中是否包含指定名称的Bean

Class getType(String name) 取回对应Bean的Class实例

boolean isSingletion(String) 测试指定的Bean之Scope是否是Singleton

String[] getAliases(String) 取Bean别名

Spring除了Bean,还提供了一些特色容器功能: org.spring-framework. context. ApplicationContext.

ApplicationContext提供了一个应用程序所需的更完整的框架功能:

1.取资源文件 2 解析文字消息 3 支持国际化 4 可以发布事件

Rod Johnson建议使用ApplicationContext取代BeanFactory.

实现ApplicationContext的类有3:

FileSystemXmlApplicationContext  ,  ClassPathXmlApplicationContext  ,  XmlWebApplicationContext

**更改一个例子片段:

public static void main(String[] args) {
 
  Resource rs = new ClassPathResource("beans-config.xml");
  BeanFactory factory = new XmlBeanFactory(rs);
  HelloBean hello = (HelloBean) factory.getBean("helloBean");

 
  System.out.println(hello.getHelloWord());
 }

更换为:


 public static void main(String[] args) {
  ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans-config.xml");
  HelloBean hello = (HelloBean) context.getBean("helloBean");

  System.out.println(hello.getHelloWord());
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值