Spring管理Bean的三种创建方式

时间:2022-11-15 21:20:39

1.使用类构造器实例化  (90%以上都是使用这种)

<bean id=“orderService" class="cn.itcast.OrderServiceBean"/>

 

2.使用静态工厂方法实例化

<bean id="personService" class="cn.itcast.service.OrderFactory" factory-method="createOrder"/>

 

 

public class OrderFactory {

  public static OrderServiceBean createOrder(){

  return new OrderServiceBean();

  }

}

 

 

3.使用实例工厂方法实例化:

     首先要实例化工厂

<bean id="personServiceFactory" class="cn.itcast.service.OrderFactory"/>

<bean id="personService" factory-bean="personServiceFactory" factory-method="createOrder"/>

 

public class OrderFactory {

  public OrderServiceBean createOrder(){

  return new OrderServiceBean();

  }

}