Spring中通过FactoryBean来配置bean
一、说在前面
实现 FactoryBean 接口在 Spring IOC 容器中配置 Bean1、Spring 中有两种类型的 Bean, 一种是普通Bean, 另一种是工厂Bean, 即FactoryBean。
2、工厂 Bean 跟普通Bean不同, 其返回的对象不是指定类的一个实例, 其返回的是该工厂 Bean 的 getObject 方法所返回的对象。
二、实例演示
Car类:
package com.at.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(String brand, double price) {
super();
this.brand = brand;
this.price = price;
}
}
CarFactoryBean类:
package com.at.beans.factorybean;
import org.springframework.beans.factory.FactoryBean;
//自定义的CarFactoryBean需要实现FactoryBean接口
public class CarFactoryBean implements FactoryBean<Car>{
private String brand;
public void setBrand(String brand) {
this.brand = brand;
}
//返回bean的对象
public Car getObject() throws Exception {
return new Car(brand,500000);
}
//返回bean的类型
public Class<?> getObjectType() {
return Car.class;
}
//是不是单实例的
public boolean isSingleton() {
return true;
}
}
<?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="car" class="com.at.beans.factorybean.CarFactoryBean">
<property name="brand" value="Audi"></property>
</bean>
</beans>
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factorybean.xml");
Car car = (Car) ctx.getBean("car");
System.out.println(car);
返回结果:
六月 01, 2017 5:07:34 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1c49094: startup date [Thu Jun 01 17:07:34 CST 2017]; root of context hierarchy
六月 01, 2017 5:07:35 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-factorybean.xml]
Car [brand=Audi, price=500000.0]
By luoyepiaoxue2014
微博地址:http://weibo.com/luoyepiaoxue2014 点击打开链接