FactoryBean
總結(jié)自:https://www.cnblogs.com/davidwang456/p/3688250.html
Spring中有兩種類型的Bean,一種是普通Bean,另一種是工廠Bean,即xxxFactoryBean返回的bean。
工廠Bean跟普通Bean不同,其不是類的一個(gè)實(shí)例,而是xxxFactoryBean的getObject方法所返回的xxx的對(duì)象(通過getObject返回對(duì)象,這是工廠bean的核心!)。
?
如何創(chuàng)建bean?
傳統(tǒng)方式,通過反射機(jī)制利用bean的class屬性指定實(shí)現(xiàn)類來實(shí)例化bean,這需要大量配置,不甚靈活,
而通過工廠bean,我們能定制實(shí)例化bean的流程。
備注:FactoryBean是一個(gè)接口,而xxxFactoryBean是實(shí)現(xiàn)了FactoryBean的類,可以生成某一個(gè)類型Bean實(shí)例。
?
Spring 自身就提供了70多個(gè)FactoryBean的實(shí)現(xiàn)。它們隱藏了實(shí)例化一些復(fù)雜bean的細(xì)節(jié),給上層應(yīng)用帶來了便利。
從Spring 3.0 開始, FactoryBean開始支持泛型,即接口聲明改為FactoryBean<T> 的形式:
package org.Springframework.beans.factory; public interface FactoryBean<T> { T getObject() throws Exception; Class<?> getObjectType(); boolean isSingleton(); }方法介紹:
T getObject():返回由FactoryBean創(chuàng)建的bean實(shí)例,如果isSingleton()返回true,則該實(shí)例會(huì)放到Spring容器中單實(shí)例緩存池中。
boolean isSingleton():返回由FactoryBean創(chuàng)建的bean實(shí)例的作用域是singleton還是prototype。
Class<T> getObjectType():返回FactoryBean創(chuàng)建的bean類型。
?
當(dāng)配置文件中<bean>的class屬性配置的實(shí)現(xiàn)類是FactoryBean時(shí),通過 getBean()方法返回的不是FactoryBean的實(shí)例,而是FactoryBean的getObject()方法所返回的對(duì)象,
這相當(dāng)于FactoryBean的getObject()代理了getBean()方法。
?
如何體現(xiàn)factoryBean的靈活?
例如:如果使用傳統(tǒng)方式配置下面Car的<bean>時(shí),Car的每個(gè)屬性分別對(duì)應(yīng)一個(gè)<property>元素標(biāo)簽
public class Car { private int maxSpeed ; private String brand ; private double price ; //get/set方法... }如果使用factoryBean
public class CarFactoryBean implements FactoryBean<Car> { private String carInfo ; public Car getObject () throws Exception { Car car = new Car () ; String [] infos = carInfo .split ( "," ) ; car.setBrand ( infos [ 0 ]) ; car.setMaxSpeed ( Integer. valueOf ( infos [ 1 ])) ; car.setPrice ( Double. valueOf ( infos [ 2 ])) ; return car; } public Class<Car> getObjectType () { return Car. class ; } public boolean isSingleton () { return false ; } public String getCarInfo () { return this . carInfo ; } // 接受逗號(hào)分割符設(shè)置屬性信息 public void setCarInfo ( String carInfo ) { this . carInfocarInfo = carInfo; } }個(gè)人理解,在設(shè)值時(shí)能有更多的個(gè)人操作,相當(dāng)于通用版和定制化的區(qū)別。
?
那么相應(yīng)的,我們應(yīng)當(dāng)這么配置:
<bean id="car" class="com.test.factorybean.CarFactoryBean" carInfo="超級(jí)跑車,400,2000000"/>注意,這是工廠bean定義bean的一般形式。
?
當(dāng)調(diào)用getBean("car") 時(shí),Spring首先通過反射機(jī)制,發(fā)現(xiàn)CarFactoryBean實(shí)現(xiàn)了FactoryBean的接口,
然后調(diào)用getObject()方法返回定制的car實(shí)例。
?
備注:如果單純希望獲取CarFactoryBean的實(shí)例,則需要在使用getBean(beanName) 方法時(shí)在beanName前顯示的加上 "&" 前綴,例如getBean("&car")。
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/yanze/p/10577217.html
總結(jié)
以上是生活随笔為你收集整理的FactoryBean的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: navigator.geolocatio
- 下一篇: 【转】DOS下文件传输---初识TCP网