Ⅸ.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的共同點 html

  1. 若是沒有顯式指定,對象的佈署模式默認爲singleton,即當修改一個實例化,再次經過id獲取, 爲修改後的實例
  2. 實現IFactoryObject|FactoryBean 接口的對象也能夠獲取這個工廠 不必定是這個工廠建立的實例,經過在id前面加上&符號

相關文章
相關標籤/搜索