基于泛型访问DI容器

为显示地访问宿主在DI容器(包括BeanFactory和ApplicationContext)中的受管Bean,开发者需要在调用getBean()方法后,完成对象的造型操作,因此编译期很难知道造型正确与否.Spring 2.x引入的GenericBeanFactoryAccessor辅助类能避免造型操作,它借用到了JDK5.0中的泛型特性.这一辅助类对DI容器进行了包裹,并提供了大量的辅助方法.

以下是一个示例:

package test; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.generic.GenericBeanFactoryAccessor; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; /** * 使用GenericBeanFactoryAccessor * * @author zxs */ public class GenericBeanFactoryAccessorDemo { protected static final Log log = LogFactory .getLog(GenericBeanFactoryAccessorDemo.class); public static void main(String[] args) { Resource res = new ClassPathResource("generic.xml"); ListableBeanFactory bf = new XmlBeanFactory(res); //同样适用于ApplicationContext GenericBeanFactoryAccessor gbf = new GenericBeanFactoryAccessor(bf); //不用进行造型 ITestBean1 tb1 = gbf.getBean("tb1"); log.info(tb1); //要求返回TestBean1类型,且id是tb2的受管Bean ITestBean1 tb2 = gbf.getBean("tb2", TestBean1.class); log.info(tb2); //返回ITestBean1类型的受管Bean集合。期间,允许返回原型Bean Map<String, ITestBean1> mapTestBean1 = gbf.getBeansOfType( ITestBean1.class, true, false); log.info(mapTestBean1); //返回那些在类一级使用了@ForYou注释的受管Bean集合 Map<String, Object> map = gbf.getBeansWithAnnotation(ForYou.class); log.info(map); } }

相关XML配置:

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="tb1" class="test.TestBean1"/> <bean id="tb2" class="test.TestBean1"/> <bean id="tb3" class="test.TestBean1" scope="prototype"/> <bean id="testBean2" class="test.TestBean2"/> </beans>

你可能感兴趣的:(基于泛型访问DI容器)