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();
}
}
import com.lz.service.imp.UserImpDao;
public class UsersFactory {
public static UserImpDao createStaticUserBean() {
return new UserImpDao();
}
}
<
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();
}
}
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
>
<
bean
name
="userFactoryBean"
factory-bean
="userFactory"
factory-method
="createUserBean"
></
bean
>
<bean name="userImpDao" class="com.lz.service.imp.UserImpDao"></bean>