spring工厂(静态工厂/实例工厂)
程序员文章站
2022-05-21 23:06:22
...
Spring 的工厂方法
- IoC 通过工厂模式创建 bean 的方式有两种:
- 静态工厂方法
- 实例工厂方法
- 工厂:用来存储生产的东西
静态工厂方法
package com.zjh.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car {
private long id;
private String name;
//无参构造 一定要有
//get set方法
}
package com.zjh.factory;
import com.zjh.entity.Car;
import java.util.HashMap;
import java.util.Map;
public class StaticCarFactory {
private static Map<Long, Car> carMap;
static{
carMap = new HashMap<Long, Car>();
carMap.put(1L,new Car(1L,"宝马"));
carMap.put(2L,new Car(2L,"奔驰"));
}
public static Car getCar(long id){
return carMap.get(id);
}
}
<!-- 配置静态工厂创建 Car -->
<bean id="car" class="com.zjh.factory.StaticCarFactory" factory-method="getCar">
<constructor-arg value="2"></constructor-arg>
</bean>
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-StaticCarFactory.xml");
Car car = (Car) applicationContext.getBean("car");
System.out.println(car);//输出 (2L,奔驰) 的Car
实例工厂方法
package com.zjh.factory;
import com.zjh.entity.Car;
import java.util.HashMap;
import java.util.Map;
public class InstanceCarFactory {
private Map<Long, Car> carMap;
public InstanceCarFactory(){
carMap = new HashMap<Long, Car>();
carMap.put(1L,new Car(1L,"宝马"));
carMap.put(2L,new Car(2L,"奔驰"));
}
public Car getCar(long id){
return carMap.get(id);
}
}
<!-- 配置实例工厂 bean -->
<bean id="carFactory" class="com.zjh.factory.InstanceCarFactory"></bean>
<!-- 配置实例工厂创建 Car -->
<bean id="car2" factory-bean="carFactory" factory-method="getCar">
<constructor-arg value="1"></constructor-arg>
</bean>
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-InstanceCarFactory.xml");
Car car = (Car) applicationContext.getBean("car2");
System.out.println(car);//输出 (1L,宝马) 的Car
上一篇: Spring bean初始化和销毁方法
下一篇: spring 中 静态工厂与实例工厂