Spring 中有两种类型的 Bean, 一种是普通Bean, 另一种是工厂Bean, 即FactoryBean.
工厂 Bean 跟普通Bean不同, 其返回的对象不是指定类的一个实例, 其返回的是该工厂 Bean 的 getObject 方法所返回的对象
为什么我们有了全类名配置,工厂方法配置,为什么还要有factorybean?
因为我们有些时候配置bean的时候,需要用到IOC容器中其他的bean,这个时候我们通过FactoryBean去配置是最合适的。
新建一个包: com.atguigu.spring.beans.factorybean
新建类Car
package com.atguigu.spring.beans.factorybean;
public class Car {
private String brand;
private double price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]";
}
public Car() {
// TODO Auto-generated constructor stub
System.out.println("Car's constructor...");
}
public Car(String brand, double price) {
super();
this.brand = brand;
this.price = price;
}
}
新建类 CarFactoryBean, 注意这个类需要实现FactoryBean接口
package com.atguigu.spring.beans.factorybean;
import org.springframework.beans.factory.FactoryBean;
// 自定义的FactoryBean需要实现 FactoryBean 接口
public class CarFactoryBean implements FactoryBean{
private String brand;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
// 返回bean的对象
@Override
public Object getObject() throws Exception {
// TODO Auto-generated method stub
return new Car(brand, 500000);
}
// 返回bean的类型
@Override
public Class getObjectType() {
// TODO Auto-generated method stub
return Car.class;
}
// 是不是单例
@Override
public boolean isSingleton() {
// TODO Auto-generated method stub
return true;
}
}
FactoryBean的三个方法及作用
getObject() :返回bean的对象
getObjectType():返回bean的类型
isSingleton():是否是单例
新建beans-factorybean.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
通过FactoryBean 来配置Bean 的实例
calss: 指向FactoryBean的全类名
property: 配置FactoryBean的属性
但实际返回的实例却是FactoryBean的 getObject() 方法返回的实例
-->
<bean id="car" class="com.atguigu.spring.beans.factorybean.CarFactoryBean">
<property name="brand" value="BMW"></property>
</bean>
</beans>
新建Main类:
package com.atguigu.spring.beans.factory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factory.xml");
Car car2 = (Car) ctx.getBean("car2");
System.out.println(car2);
}
}
输出结果如下:
Car [brand=BMW, price=500000.0]
综上: 在进行FactoryBean配置的时候,首先需要实现FactoryBean接口,其次,calss: 指向FactoryBean的全类名,property: 配置FactoryBean的属性,但真正返回的实例却是FactoryBean的 getObject() 方法中返回的实例。本例子中返回的是Car实例,而非FactoryBean实例。