在 Spring 框架中,如果您想通过调用静态工厂方法来创建 bean ,其目的是将对象创建过程封装在static
方法中,那么您可以使用factory-method
属性。
静态工厂方法示例
如果你想EmployeeDTO
基于它designation
使用静态工厂方法创建不同的对象,你可以像下面的例子那样做。
public class EmployeeDTO {
private Integer id;
private String firstName;
private String lastName;
private String designation;
//Setters and Getters
@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName
+ ", lastName=" + lastName + ", type=" + designation + "]";
}
}
创建静态工厂方法。
public class EmployeeFactory {
public static EmployeeDTO createEmployeeOfType(String type)
{
if ("manager".equals(type) || "director".equals(type))
{
EmployeeDTO employee = new EmployeeDTO();
employee.setId(-1);
employee.setFirstName("dummy");
employee.setLastName("dummy");
//Set designation here
employee.setDesignation(type);
return employee;
}
else
{
throw new IllegalArgumentException("Unknown product");
}
}
}
使用factory-method
属性来创建 bean。
<bean id="manager" class="com.leftso.demo.factory.EmployeeFactory"
factory-method="createEmployeeOfType">
<constructor-arg value="manager" />
</bean>
<bean id="director" class="com.leftso.demo.factory.EmployeeFactory"
factory-method="createEmployeeOfType">
<constructor-arg value="director" />
</bean>
演示
让我们测试一下静态工厂方法配置。
public class TestSpringStaticFactoryMethod
{
@SuppressWarnings("resource")
public static void main(String[] args) throws Exception
{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeDTO manager = (EmployeeDTO) context.getBean("manager");
System.out.println(manager);
EmployeeDTO director = (EmployeeDTO) context.getBean("director");
System.out.println(director);
}
}
在控制台中观察输出:
Employee [id=-1, firstName=dummy, lastName=dummy, type=manager]
Employee [id=-1, firstName=dummy, lastName=dummy, type=director]
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/243593.html