public class CarFactory {
//非静态方法
public Car createCar(){
Car car = new Car();
car.setBrand("BMW");
return car;
}
//静态方法
public static Car createStaticCar(){
Car car = new Car();
return car;
}
}
1.对于非静态方法createCar的注入方式:
非静态方法:必须实例化工厂类(factory-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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 工厂方法-->
<bean id="carFactory" class="com.baobaotao.ditype.CarFactory" />
<bean id="car5" factory-bean="carFactory" factory-method="createCar">
</bean>
</beans>
2.对于静态方法createStaticCar的注入方式:
静态方法:无须创建工厂类实例的情况下就可以调用工厂类方法
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="car6" class="com.baobaotao.ditype.CarFactory" factory-method="createStaticCar"></bean>
</beans>
总结:
factory-bean:用于实例化工厂类;
factory-method:用于调用工厂类方法。