在工厂设计模式中,我们不会直接调用类的构造方法来创建对象,而是通过工厂类来创建。
Bean中也支持这样创建:
<bean class="com.test.bean.StudentFactory" factory-method="getStudent"/>
这里的class指的是工厂类,但返回的是调用 getStudent 后得到的Student类。
但此时对于静态的getStudent方法,我们没法通过配置文件对Bean进行依赖注入等操作。需要将工厂类的静态方法改为默认,并再定义一个工厂Bean:
<bean name="studentFactory" class="com.test.bean.StudentFactory"/>
<bean factory-bean="studentFactory" factory-method="getStudent"/>
此时就可以在第二个bean中设置该类的生命周期。
获取
如果我们想获取工厂Bean为我们提供的Bean,可以直接输入工厂Bean的名称,这样不会得到工厂Bean的实例,而是工厂Bean生产的Bean的实例:
Student bean = (Student) context.getBean("studentFactory");
如果想获得工厂Bean,则需要加上 &
:
StudentFactory bean = (StudentFactory) context.getBean("&studentFactory");