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

使用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

你可能感兴趣的:(bean,xml)