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

本文介绍如何通过实现Spring框架中的FactoryBean接口来简化自定义工厂Bean的开发过程。文章展示了具体的代码示例,包括如何定义一个返回Chinese对象的PersonFactory类,并通过配置文件在Spring上下文中注册该工厂Bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用FactoryBean接口简化工厂Bean开发,但是,一个工厂只能有一类产品

public class PersonFactory implements FactoryBean
... {
Personp
=null;
//返回产品
publicObjectgetObject()throwsException
...{
if(p==null)
...{
p
=newChinese();
}

returnp;
}

//返回产品类型
publicClassgetObjectType()
...{
returnChinese.class;
}

//产生的实例是否为单态
publicbooleanisSingleton()
...{
returntrue;
}

}


配置文件:


< beans >


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


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

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

Stringpath
=newTest().getClass().getResource("/").getPath();
Stringrealpath
=path.substring(1,path.length());
ApplicationContextcontext
=newFileSystemXmlApplicationContext(realpath+"/beanfactory.xml");

Chinesep
=(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值