當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring 利用FactoryBean来配置Bean
生活随笔
收集整理的這篇文章主要介紹了
Spring 利用FactoryBean来配置Bean
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Spring 利用FactoryBean來配置Bean
在之前的 博文 已經介紹可以利用java反射機制 和 工廠方法(Factory Method)的方法來在bean config file里 配置beans
本文簡單介紹下第三種方法 FactoryBean。
FactoryBean 用法可以與Factory Method有點類似,我們同樣需要寫1個工廠類, 只不過spring提供了1個叫做FactoryBean的接口。
我們的工廠類必須實現這個接口。
例子
我們首先寫1個Car類
package com.home.factoryBean;public class Car {private int id;private String name;private int price;@Overridepublic String toString() {return "Car [id=" + id + ", name=" + name + ", price=" + price + "]";}public Car(){}public Car(int id, String name, int price) {super();this.id = id;this.name = name;this.price = price;} }接下來必須寫1個工廠類CarBeanFactory
package com.home.factoryBean;import org.springframework.beans.factory.FactoryBean;public class CarBeanFactory implements FactoryBean<Car>{private int id;private String brand;public void setId(int id) {this.id = id;}public void setBrand(String brand) {this.brand = brand;}@Overridepublic Car getObject() throws Exception {return new Car(id, brand, 0);}@Overridepublic Class<?> getObjectType() {return Car.class;}@Overridepublic boolean isSingleton() {return true;}}首先上面這個工廠必須實現Spring提供的FactoryBean這個接口。
然后重寫里面的3個方法
getObject() -> 這個就是你想利用工廠類生產的bean對象, 通常在里面new 1個 對象就ok
getObjectType() -> 你必須指明上面bean的對象的class
isSingleton() -> 這個方法決定了這個bean是否單例的。
bean 配置文件
<!-- FactroyBean:* We should specify the full class name of Factory to the property "class="* Actually this bean will return the object from the method "getObject" of the Factory class.--><bean id="car1" class="com.home.factoryBean.CarBeanFactory"><property name="id" value="1"></property><property name="brand" value="Ford"></property> </bean>里面bean的配置寫法跟反射機制的十分類似。
但是一般利用反射機制的bean配置, class= 的值就是bean對象的全類名, 但是利用FactoryBean的方式中, class= 必須是工廠類的全類名。
一但這個工廠類實現了FactoryBean接口, 那么這個bean item 返回的就是它里面的getObject()方法return的對象。
client代碼
package com.home.factoryBean;import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class FactoryBeanClient {public static void f(){ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-FactoryBean.xml");Car car1 = (Car)ctx.getBean("car1");System.out.println(car1);}輸出結果
Jun 04, 2016 1:26:00 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@627e9505: startup date [Sat Jun 04 13:26:00 CST 2016]; root of context hierarchy Jun 04, 2016 1:26:00 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [bean-FactoryBean.xml] Car [id=1, name=Ford, price=0] 《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Spring 利用FactoryBean来配置Bean的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java 动态代理介绍及用法
- 下一篇: Spring AOP 简介以及简单用法