静态工厂方法及实例工厂的使用:
applicationContext.xml:
<!-- factory-method 是指调用静态工厂方法 -->
<bean id="helloWorld2" class="com.lee.spring002.createobject.method.HelloWorldFactory"
factory-method="getInstance"></bean>
<!-- 实例工厂 -->
<bean id="helloWorldFactory"
class="com.lee.spring002.createobject.method.HelloWorldFactory2"></bean>
<!-- factory-bean 是一个工厂bean -->
<bean id="helloWorld3" factory-bean="helloWorldFactory"
factory-method="getInstance"></bean>
HelloWorldFactory.java
package com.lee.spring002.createobject.method;
import com.lee.spring001.createobject.HelloWorld;
public class HelloWorldFactory {
public static HelloWorld getInstance() {
return new HelloWorld();
}
}
HelloWorldFactory2.java
package com.lee.spring002.createobject.method;
import com.lee.spring001.createobject.HelloWorld;
public class HelloWorldFactory2 {
public HelloWorld getInstance() {
return new HelloWorld();
}
}
测试:
@Test
public void testHelloWorld_StaticFactory() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld hello = (HelloWorld)context.getBean("helloWorld2");
hello.hello();
}
@Test
public void testHelloWorld_InstanceFactory() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld hello = (HelloWorld)context.getBean("helloWorld3");
hello.hello();
}