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

来源:互联网 发布:淘宝如何投诉假冒商品 编辑:程序博客网 时间:2024/05/18 00:35

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

 
原创粉丝点击