Spring getBeansofType

//////////////////////////////////
如何载入所有同类型的bean
//////////////////////////////////

使用BeanFatory的 getBeansOfType()方法,该方法返回一个Map类型的实例,Map中的key为Bean的名,key对应的内容为Bean的实例。

该方法有两种类型的重载

getBeansOfType(Class),获取某一类的所有的bean。

getBeansOfType(Class,boolean,boolean),后面两个布尔值,第一代表是否也包含原型(Class祖先)bean或者或者只是singletons(包含FactoryBean生成的),第二个表示是否立即实例化懒加载或者由FactoryBean生成的Bean以保证依赖关系。

例程代码:

配置如下

   
     Hello!Justin!
   


   
       Hello!caterpillar!
   

程序如下
Map helloBeans = factory.getBeansOfType(HelloBean.class, false, false);


在applicationContext.xml配置文件中,有如下的bean配置
 <!-- 使用托管方式的disconf配置(无代码侵入, 配置更改会自动reload)-->
    <bean id="configproperties_disconf"
          class="com.baidu.disconf.client.addons.properties.ReloadablePropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath:/autoconfig.properties</value>
                <value>classpath:/autoconfig2.properties</value>
                <value>classpath:/myserver_slave.properties</value>
                <value>classpath:/testJson.json</value>
                <value>testXml2.xml</value>
            </list>
        </property>
    </bean>
    <bean id="configproperties_no_reloadable_disconf"
          class="com.baidu.disconf.client.addons.properties.ReloadablePropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>myserver.properties</value>
            </list>
        </property>
    </bean>


使用applicationContext方法getBeansOfType()得当的map如下所示

Class<ReloadablePropertiesFactoryBean> type = ReloadablePropertiesFactoryBean.class;
            
            Map<String, ReloadablePropertiesFactoryBean>  map = applicationContext.getBeansOfType(type);
            
            System.out.println("map="+map.toString());


map={&configproperties_disconf=ReloadablePropertiesFactoryBean, &configproperties_no_reloadable_disconf=ReloadablePropertiesFactoryBean}

参考:http://blog.sina.com.cn/s/blog_5d03c2970102wa87.html

猜你喜欢

转载自rd-030.iteye.com/blog/2322154