Spring 中有两种类型的 Bean, 一种是普通Bean, 另一种是工厂Bean, 即FactoryBean.
工厂 Bean 跟普通Bean不同, 其返回的对象不是指定类的一个实例, 其返回的是该工厂 Bean 的 getObject 方法所返回的对象
1.1 创建bean:
package spring.demo_01.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; } public Car(String brand, double price) { super(); this.brand = brand; this.price = price; } @Override public String toString() { return "Car [brand=" + brand + ", price=" + price + "]"; } }
1.2 创建MyFactoryBean 实现接口FactoryBean
package spring.demo_01.factorybean; import org.springframework.beans.factory.FactoryBean; public class MyFactoryBean implements FactoryBean<Car> { private String brand; public void setBrand(String brand) { this.brand = brand; } @Override public Car getObject() throws Exception { return new Car(brand,30000); } @Override public Class<?> getObjectType() { return Car.class; } @Override public boolean isSingleton() { return true; } }
1.3 配置bean:
<?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="spring.demo_01.factorybean.MyFactoryBean"> <property name="brand" value="BMW"></property> </bean> </beans>
1.4 测试类:
package spring.demo_01.factorybean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { @SuppressWarnings("resource") public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factorybean.xml"); Car car = ctx.getBean("car",Car.class); System.out.println(car); } }
时间: 2024-10-14 12:27:53