读书人

Spring 2-见见容器中有什么

发布时间: 2012-09-23 10:28:11 作者: rapoo

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. 转化为BeanDefinitionRegistryBeanDefinitionRegistry beanDefinitionRegistry = null;if (beanFactory instanceof BeanDefinitionRegistry) {beanDefinitionRegistry = (BeanDefinitionRegistry) beanFactory;}if (beanDefinitionRegistry == null) {throw new RuntimeException("listableBeanFactory is null.");}
?上面的示例代码中,ListableBeanFactory和BeanDefinitionRegistry两个接口单独说明一下
    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实例,客户端甚至可以通过名字来查找;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);        // 判断是否是抽象的beanif (bd.isAbstract()) {System.out.println("\tIt is a abstract bean.");                continue;}IBean bean = (IBean) beanFactory.getBean(name);System.out.print("\t");bean.doItNow();}

读书人网 >软件架构设计

热点推荐