1. 静态工厂方法
直接调用某个类的静态方法就可以返回bean的实例
写一个用静态工厂配置的类
Car.java
package spring.factory;
public class Car {
private String brand;
private double price;
public void setBrand(String brand) {
this.brand = brand;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
public String getBrand() {
return brand;
}
@Override
public String toString() {
return "Car{" +
"brand='" + brand + '\'' +
", price=" + price +
'}';
}
public Car(String brand,double price){
this.brand = brand;
this.price = price;
}
}
写静态工厂类
StaticCarFactory.java
public class StaticCarFactory {
private static Map<String,Car> carMap = new HashMap<String, Car>();
static {
carMap.put("aodi" ,new Car("aodi",3000));
carMap.put("fute" ,new Car("fute",9000));
}
public static Car getCar(String name){
return carMap.get(name);
}
}
配置xml文件
<!-- 通过静态工厂方法来配置bean。注意配置的是bean的实例而不是静态工厂 -->
<!-- class属性:指向静态工厂全类名
factory-method:指向静态工厂的名字
constructor-arg:如果静态工厂需要参数则用其指定
-->
<bean id="car1" class="spring.factory.StaticCarFactory" factory-method="getCar">
<constructor-arg value="aodi"></constructor-arg>
</bean>
运行结果
2. 实例工厂方法
实例化工厂的方法,即需要创建工厂本身,在调用工厂的实例方法来返回bean的实例
写实例工厂类
InstanceCarFactory.java
public class InstanceCarFactory {
private Map<String, Car> carMap = null;
InstanceCarFactory(){
carMap = new HashMap<String, Car>();
carMap.put("aodi" ,new Car("aodi",3000));
carMap.put("fute" ,new Car("fute",9000));
}
public Car getCar(String name){
return carMap.get(name);
}
}
配置xml文件
<!-- 配置工厂实例-->
<bean id="carFactory" class="spring.factory.InstanceCarFactory"></bean>
<!-- 通过实例工厂方法来配置bean-->
<!-- class属性:指向静态工厂全类名
factory-bean:指向实例工厂的bean
factory-method:指向静态工厂的名字
constructor-arg:如果静态工厂需要参数则用其指定
-->
<bean id="car2" factory-bean="carFactory" factory-method="getCar">
<constructor-arg value="fute"></constructor-arg>
</bean>
主函数
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans-factory.xml");
Car car = (Car) applicationContext.getBean("car2");
System.out.println(car);
}
运行结果
3. 通过FactoryBean
通过实现spring提供的FactoryBean接口来进行对bean的实例化
创建一个类来实现FactoryBean接口
CarFactoryBean.java
public class CarFactoryBean implements FactoryBean<Car> {
String brean;
public void setBrean(String brean) {
this.brean = brean;
}
// 返回bean的对象
public Car getObject() throws Exception {
return new Car(brean,50000);
}
// 返回bean的类型
public Class<?> getObjectType() {
return Car.class;
}
// 是否为单实例
public boolean isSingleton() {
return true;
}
}
配置xml文件
<!--
通过FactoryBean来配置Bena实例
class:指向的是FactoryBean的全类名
property: 配置FactoryBean的属性
实际返回的实例就是实现了FactoryBean接口中的getObject()函数所返回的对象
-->
<bean id="car" class="spring.factoryBean.CarFactoryBean">
<property name="brean"><value>BYD</value></property>
</bean>
运行主函数的到结果