Ⅸ.spring的点点滴滴--IObjectFactory与IFactoryObject的杂谈

承接上文

ObjectFactory与IFactoryObject的杂谈


.net篇(环境为vs2012+Spring.Core.dll v1.31

    public class parent    {

        public string Name { get; set; }

        public int Age { get; set; }

    }

    public class CustomFactory :

    Spring.Objects.Factory.IFactoryObject

    {

        public object GetObject(){

            return "1";

        }

        public bool IsSingleton{

            get { return false; }

        }

        public Type ObjectType{

            get { return typeof(string); }

        }

    }
  <object id="p1" type="SpringBase.parent,SpringBase">

    <property name="Name" value="cnljli" />

    <property name="Age" value="1"/>

  </object>

  <object id="p2" type="SpringBase.parent,SpringBase" singleton="false" >

    <property name="Name" value="cnljli" />

    <property name="Age" value="1"/>

  </object>

  <object id="customFac" type="SpringBase.CustomFactory, SpringBase"/>
  1. 可以直接调用xml配置文件来返回一个工厂
     Spring.Core.IO.IResource input = new Spring.Core.IO.FileSystemResource("factory.xml");
    
             Spring.Objects.Factory.Xml.XmlObjectFactory factory =
    
             new Spring.Objects.Factory.Xml.XmlObjectFactory(input);
  2. 可以通过xml文件里面的配置为程序的实例注入, 第一个参数为实例的引用地址,第二个参数为xml文件的id
     parent ioc = new parent();
    
     factory.ConfigureObject(ioc, "p1");

java篇(环境为Maven+Jdk1.7+IntelliJ IDEA 12.1.4

package springdemo;

import org.springframework.beans.BeansException;

import org.springframework.beans.factory.*;

public class Parent {

    private String name;

    private Integer age;

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public Integer getAge() {

        return age;

    }

    public void setAge(Integer age) {

        this.age = age;

    }

}

class  CustomFactory implements FactoryBean<String>{

    @Override

    public String getObject() throws Exception {

        return "1";

    }

    @Override

    public Class<?> getObjectType() {

        return String.class;

    }

    @Override

    public boolean isSingleton() {

        return false;

    }

}
    <bean id="p1" class="springdemo.Parent">

        <property name="name" value="cnljli-p1" />

        <property name="age" value="1" />

    </bean>

    <bean id="p2" class="springdemo.Parent" singleton="false">

        <property name="name" value="cnljli-p2" />

        <property name="age" value="1" />

    </bean>

    <bean id="customFac" class="springdemo.CustomFactory" />

javaCsharp的共同点

  1. 如果没有显式指定,对象的布署模式默认为singleton,即当修改一个实例化,再次通过id获取, 为修改后的实例
  2. 实现IFactoryObject|FactoryBean 接口的对象也可以获取这个工厂 不一定是这个工厂创建的实例,通过在id前面加上&符号

你可能感兴趣的:(factory)