使用實列工廠方法時,配置Bean的實列<bean>無須配置class屬性,由於Spring容器再也不直接實列化該Bean,Spring容器僅僅調用實列工廠的工廠方法,工廠方法負責建立Bean實列。java
下面先定義Person接口,PersonFactory工廠產生的全部對象都實現Person接口:spring
package com.custle.spring.inter; /** * Created by admin on 2018/3/1. */ public interface Person { public String sayHello(String name);//定義一個打招呼的方法 public String sayGoodBye(String name);//定義一個告別方法 }
Person實列類Chinese:app
package com.custle.spring.impl; import com.custle.spring.inter.Person; /** * Created by admin on 2018/3/1. */ public class Chinese implements Person { @Override public String sayHello(String name) { return name + ",您好!"; } @Override public String sayGoodBye(String name) { return name + ",再見!"; } }
Person實列類American:ide
package com.custle.spring.impl; import com.custle.spring.inter.Person; /** * Created by admin on 2018/3/1. */ public class American implements Person{ @Override public String sayHello(String name) { return name + ",Hello!"; } @Override public String sayGoodBye(String name) { return name + ",GoodBye!"; } }
定義PersonFactory工廠:測試
package com.custle.spring.factory; import com.custle.spring.impl.American; import com.custle.spring.impl.Chinese; import com.custle.spring.inter.Person; /** * Created by admin on 2018/3/1. */ public class PersonFactory { public Person getPerson(String arg){ if(arg.equals("chinese")){ return new Chinese(); }else{ return new American(); } } }
在XML中配置:code
<!--配置工廠Bean,該Bean負責產生其餘Bean實列--> <bean id="personFactory" class="com.custle.spring.factory.PersonFactory"/> <!--採用實列工廠建立Bean實列,factory-bean指定對應的工廠Bean,factory-method指定工廠方法--> <bean id="chinese" factory-bean="personFactory" factory-method="getPerson"> <!--工廠中getPerson方法參數注入--> <constructor-arg value="chinese"/> </bean> <bean id="american" factory-bean="personFactory" factory-method="getPerson"> <!--工廠中getPerson方法參數注入--> <constructor-arg value="american"/> </bean>
factory-bean指定了實列工廠Bean的Id,factory-method指定了實列工廠的方法,constructor-arg指定了工廠方法注入的參數;xml
測試程序:對象
package com.custle.spring.test; import com.custle.spring.inter.Person; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by admin on 2018/3/1. */ public class PersonTest { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-spring.xml"); Person chinese = applicationContext.getBean("chinese", Person.class); System.out.println(chinese.sayGoodBye("小明")); System.out.println(chinese.sayHello("小明")); Person american = applicationContext.getBean("american", Person.class); System.out.println(american.sayGoodBye("xiaoming")); System.out.println(american.sayHello("xiaoming")); } }
控制檯輸出:接口
小明,再見! 小明,您好! xiaoming,GoodBye! xiaoming,Hello!
調用實列工廠方法建立Bean,與調用靜態工廠建立Bean的用法基本類似。區別以下:get
調用實列工廠建立Bean,必須將實列工廠配置成Bean實列。而靜態工廠方法建立Bean,則無須配置工廠Bean。
調用實列工廠方法建立Bean,必須使用factory-bean屬性肯定工廠Bean。而靜態工廠方法建立Bean,則使用class元素肯定靜態工廠類。