Spring 2-看看容器中有什么

一、初始化

// 1. 资源
Resource res = new ClassPathResource("beans.xml");

// 2. 初始化IOC容器
BeanFactory beanFactory = new XmlBeanFactory(res);
 

二、如何查看容器中的bean定义信息?

// 3. 转化为可枚举容器
ListableBeanFactory listableBeanFactory = null;
if (beanFactory instanceof ListableBeanFactory) {
	listableBeanFactory = (ListableBeanFactory) beanFactory;
}
if (listableBeanFactory == null) {
	throw new RuntimeException("listableBeanFactory is null.");
}

// 4. 转化为BeanDefinitionRegistry
BeanDefinitionRegistry beanDefinitionRegistry = null;
if (beanFactory instanceof BeanDefinitionRegistry) {
	beanDefinitionRegistry = (BeanDefinitionRegistry) beanFactory;
}
if (beanDefinitionRegistry == null) {
	throw new RuntimeException("listableBeanFactory is null.");
}
 
上面的示例代码中,ListableBeanFactory和BeanDefinitionRegistry两个接口单独说明一下
  1. ListableBeanFactory
    这是接口的注释:
    Extension of the BeanFactory interface to be implemented by bean factories that can enumerate all their bean instances, rather than attempting bean lookup by name one by one as requested by clients.
    该接口继承自BeanFactory,同时该容器能枚举它的bean实例,客户端甚至可以通过名字来查找;
  2. BeanDefinitionRegistry
    注释:
    Interface for registries that hold bean definitions, for example RootBeanDefinition and ChildBeanDefinition instances. Typically implemented by BeanFactories that internally work with the AbstractBeanDefinition hierarchy.
    实现该接口,可以拿到注册到容器中的bean的定义信息,包括抽象的bean定义;
遍历容器中的bean
for (String name : listableBeanFactory.getBeanDefinitionNames()) {
        // 对每一个bean的name,从BeanDefinitionRegistry中拿到BeanDefinition信息
	BeanDefinition bd = beanDefinitionRegistry.getBeanDefinition(name);
	System.out.println(name);

        // 判断是否是抽象的bean
	if (bd.isAbstract()) {
		System.out.println("\tIt is a abstract bean.");
                continue;
	}

	IBean bean = (IBean) beanFactory.getBean(name);
	System.out.print("\t");
	bean.doItNow();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值