配置Bean的第三种方式:FactoryBean
FactoryBean需要实现FactoryBean接口,接口中有三个方法:
- getObject()
- getObjectType()
- isSingleton()
FactoryBean.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| package factoryBean;
public class FactoryBean implements org.springframework.beans.factory.FactoryBean<Car> {
private String brand;
public void setBrand(String brand) { this.brand = brand; }
@Override public Car getObject() throws Exception { return new Car(brand, 100, 400000); }
@Override public Class<?> getObjectType() { return Car.class; }
@Override public boolean isSingleton() { return true; } }
|
Car.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| package factoryBean;
class Car { private String brand; private int speed; private double price;
Car(String brand, int speed, double price) { this.brand = brand; this.speed = speed; this.price = price; }
@Override public String toString() { return "Car{" + "brand='" + brand + '\'' + ", speed=" + speed + ", price=" + price + '}'; }
public void setBrand(String brand) { this.brand = brand; }
public void setSpeed(int speed) { this.speed = speed; }
public void setPrice(double price) { this.price = price; } }
|
Main.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package factoryBean;
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("factoryBean/BeanFactory.xml"); Car car = (Car) applicationContext.getBean("car"); System.out.println(car); } }
|
BeanFactory.xml
1 2 3 4 5 6 7 8 9 10 11 12 13
| <?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">
<bean id="car" class="factoryBean.FactoryBean"> <property name="brand" value="Audi"/> </bean> </beans>
|
运行结果为:
1
| Car{brand='Audi', speed=100, price=400000.0}
|