工厂方法创建bean
工厂方法为Spring提供了创建bean的另外一种方式,属于工厂设计模式,为bean的创建提供了更大的灵活性,屏蔽了复杂对象的创建过程。
静态工厂方法
用法:
<bean id="user" class="com.bailiban.day2.factory.staticfactory.StaticFactory" factory-method="getUser" />
- class: 设置静态工厂方法类
- factory-method: 指定生产该bena的静态方法;
示例:
静态工厂方法类:
/**
* 静态工厂方法
*/
public class StaticFactory {
public static User getUser() {
return new User(1001, "Jim");
}
public static UserDao getUserDao() {
return new UserDaoImpl();
}
}
配置文件:
<!-- class: 静态工厂方法类
factory-method:用于生产指定对象的静态工厂方法
-->
<bean id="user" class="com.bailiban.day2.factory.staticfactory.StaticFactory" factory-method="getUser" />
<bean id="userDao" class="com.bailiban.day2.factory.staticfactory.StaticFactory" factory-method="getUserDao" />
测试:
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"com/bailiban/day2/factory/staticfactory/staticFactory.xml");
User user = (User) context.getBean("user");
System.out.println(user);
UserDao userDao = (UserDao) context.getBean("userDao");
System.out.println(userDao);
}
运行结果:
User{id=1001, name='Jim'}
com.bailiban.day1.helloworld.dao.impl.UserDaoImpl@55fe41ea
实例工厂方法
用法:
<bean id="instanceFactory" class="com.bailiban.day2.factory.instancefactory.InstanceFactory" />
<bean id="user" factory-bean="instanceFactory" factory-method="getUser" />
- 指定实例工厂bean:instanceFactory;
- 在待生产的bean中,指定:
- factory-bean: 实例工厂方法bean;
- factory-method: 指定生产该bean的工厂方法;
示例:
实例工厂方法类:
/**
* 实例工厂方法
*/
public class InstanceFactory {
public User getUser() {
return new User(1001, "Jim");
}
public UserDao getUserDao() {
return new UserDaoImpl();
}
}
配置文件:
<bean id="instanceFactory" class="com.bailiban.day2.factory.instancefactory.InstanceFactory" />
<!-- factory-bean: 实例工厂方法bean
factory-method:指定生产该bean的工厂方法
-->
<bean id="user" factory-bean="instanceFactory" factory-method="getUser" />
<bean id="userDao" factory-bean="instanceFactory" factory-method="getUserDao" />
测试:
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"com/bailiban/day2/factory/instancefactory/instanceFactory.xml");
User user = (User) context.getBean("user");
System.out.println(user);
UserDao userDao = (UserDao) context.getBean("userDao");
System.out.println(userDao);
}
运行结果:
User{id=1001, name='Jim'}
com.bailiban.day1.helloworld.dao.impl.UserDaoImpl@55fe41ea