- Spring 中有两种类型的 Bean, 一种是普通Bean, 另一种是工厂Bean, 即FactoryBean.
- 工厂 Bean 跟普通Bean不同, **其返回的对象不是指定类的一个实例, 其返回的是该工厂 Bean 的 getObject 方法所返回的对象 **
下面是FactoryBean接口中的方法
演示:
Car_FactoryBean.java
package com.atguigu.spring.bean;
import org.springframework.beans.factory.FactoryBean;
//自定义的FactoryBean,需要实现FactoryBean的接口
public class Car_FactoryBean implements FactoryBean<Car> {
private String brand;
public void setBrand(String brand) {
this.brand=brand;
}
//返回bean的对象
@Override
public Car getObject() {
return new Car(brand, 80000);
}
//返回bean的类型
@Override
public Class<?> getObjectType(){
return null;
}
@Override
public boolean isSingleton() {
return false;
}
}
Car.java
package com.atguigu.spring.bean;
public class Car {
private String brand;
private double price;
public Car(String brand, double price) {
super();
this.brand = brand;
this.price = price;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]";
}
}
application.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的实例
class:指向 FactoryBean的全类名
property:配置FactoryBean的属性
但实际返回的实例却是FactoryBean的getObject方法返回的实例!
-->
<bean id="car1" class="com.atguigu.spring.bean.Car_FactoryBean">
<property name="brand" value="bmw"></property>
</bean>
</beans>
Main.java
package com.atguigu.spring.bean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("application.xml");
Car car1=(Car) applicationContext.getBean("car1");
System.out.println(car1);
}
}