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();
}

你可能感兴趣的:(spring,bean,xml,IOC)