Spring提供了三种实例化Bean的方式:
第一种:使用类构造器实例化(最常用)
<bean name="userImpDao" class="com.lz.service.imp.UserImpDao"></bean>
第二种:使用静态工厂方法实例化
UsersFactory:
package com.lz.factory;
import com.lz.service.imp.UserImpDao;
public class UsersFactory {
public static UserImpDao createStaticUserBean() {
return new UserImpDao();
}
}
再把UsersFactory类交给Spring管理
<bean name="userStaticFactory" class="com.lz.factory.UsersFactory" factory-method="createStaticUserBean"></bean>
第三种:使用实例工厂方法实例化
UsersFactory:
package com.lz.factory;
import com.lz.service.imp.UserImpDao;
public class UsersFactory {
public UserImpDao createUserBean() {
return new UserImpDao();
}
}
再在Spring配置文件中实例化 UsersFactory类:
<bean name="userFactory" class="com.lz.factory.UsersFactory"></bean>
然后再指定上述配置文件中的"userFactory"这个Bean中的"createUserBean"方法来实例化Bean:
<bean name="userFactoryBean" factory-bean="userFactory" factory-method="createUserBean"></bean>
最后对"userFactoryBean"进行测试! 成功!
<bean name="userImpDao" class="com.lz.service.imp.UserImpDao"></bean>