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

被折叠的 条评论
为什么被折叠?



