[ * ] 静态工程方法创建bean
[ * ] 实例工程方法创建bean
[ * ] spring的FactoryBean创建bean
静态工程方法创建bean
直接用类的静态方法就可以返回bean的实例
public class StaticCarFactory {
private static Map<String, Car> cars = new HashMap<String, Car>();
static {
cars.put("audi", new Car("audi", 20000));
cars.put("ford", new Car("ford", 40000));
}
public static Car getCar(String name) {
return cars.get(name);
}
}
<!-- 通过静态工程方法配置bean
注意:不是配置静态工程方法实例,而是配置bean实例
class 属性:指向静态工程方法全类名称
factory-method: 指向静态工程方法
constructor-arg:如果静态工程方法需要传入参数,这个使用constructor-arg: 配置参数
-->
<bean id="car1"
class="com.sunny.beans.factory.StaticCarFactory"
factory-method="getCar">
<constructor-arg name="name" value="audi"/>
</bean>
静态工程方法创建bean
先创建工程本身,在调用工程的实例方法
public class InstanceCarFactory {
private static Map<String, Car> cars;
public InstanceCarFactory() {
cars = new HashMap<String, Car>();
cars.put("audi", new Car("audi", 20000));
cars.put("ford", new Car("ford", 40000));
}
public Car getCar(String name) {
return cars.get(name);
}
}
<!--通过实例的工程方法创建bean-->
<!--配置工程实例-->
<bean id="carFactory"
class="com.sunny.beans.factory.InstanceCarFactory"/>
<bean id="car2"
factory-bean="carFactory"
factory-method="getCar">
<constructor-arg name="name" value="ford"/>
</bean>
spring的FactoryBean创建bean
实现FactoryBean接口
public class CarFactoryBean implements FactoryBean<Car> {
private String brand;
public void setBrand(String brand) {
this.brand = brand;
}
/**
* @return bean对象
* @throws Exception 异常
*/
@Override
public Car getObject() throws Exception {
return new Car(brand, 40000);
}
/**
* @return bean的类型
*/
@Override
public Class<?> getObjectType() {
return Car.class;
}
/**
* @return 是否单例
*/
@Override
public boolean isSingleton() {
return true;
}
}
<bean id="car3"
class="com.sunny.beans.factory.CarFactoryBean">
<property name="brand" value="CarFactoryBean"/>
</bean>