您的位置:首页 > 其它

使用FactoryBean接口简化工厂Bean开发

2007-04-06 10:03 543 查看
使用FactoryBean接口简化工厂Bean开发,但是,一个工厂只能有一类产品


public class PersonFactory implements FactoryBean




...{


Person p = null;


//返回产品


public Object getObject() throws Exception




...{


if (p == null)




...{


p = new Chinese();


}


return p;


}


//返回产品类型


public Class getObjectType()




...{


return Chinese.class;


}


//产生的实例是否为单态


public boolean isSingleton()




...{


return true;


}


}

配置文件:




<beans>






<bean id="beanfactory" class="Bean.Beanfactory.PersonFactory">


</bean>


</beans>

这样,根据beanfactory获得的bean不再是PersonFactory,而是其产品Chinese,如果需要得到PersonFactory实例,有另外一种调用方式,如下:




public static void main(String[] args) throws Exception ...{




String path=new Test().getClass().getResource("/").getPath();


String realpath=path.substring(1, path.length());


ApplicationContext context=new FileSystemXmlApplicationContext(realpath+"/beanfactory.xml");




Chinese p=(Chinese)context.getBean("beanfactory");


System.out.println(context.getBean("&beanfactory"));


System.out.println(p);




}




其中System.out.println(context.getBean("&beanfactory"));返回工厂的实例

运行结果:

Bean.Beanfactory.PersonFactory@ca470
Bean.Beanfactory.Chinese@1ffc686
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: