Spring 一二事(2)
静态工厂方法及实例工厂的使用:
applicationContext.xml:
1 <!-- factory-method 是指调用静态工厂方法 --> 2 <bean id="helloWorld2" class="com.lee.spring002.createobject.method.HelloWorldFactory" 3 factory-method="getInstance"></bean> 4 5 <!-- 实例工厂 --> 6 <bean id="helloWorldFactory" 7 class="com.lee.spring002.createobject.method.HelloWorldFactory2"></bean> 8 <!-- factory-bean 是一个工厂bean --> 9 <bean id="helloWorld3" factory-bean="helloWorldFactory" 10 factory-method="getInstance"></bean>
HelloWorldFactory.java
1 package com.lee.spring002.createobject.method; 2 3 import com.lee.spring001.createobject.HelloWorld; 4 5 public class HelloWorldFactory { 6 7 public static HelloWorld getInstance() { 8 return new HelloWorld(); 9 } 10 }
HelloWorldFactory2.java
1 package com.lee.spring002.createobject.method; 2 3 import com.lee.spring001.createobject.HelloWorld; 4 5 public class HelloWorldFactory2 { 6 7 public HelloWorld getInstance() { 8 return new HelloWorld(); 9 } 10 }
测试:
1 @Test 2 public void testHelloWorld_StaticFactory() { 3 4 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 5 6 HelloWorld hello = (HelloWorld)context.getBean("helloWorld2"); 7 hello.hello(); 8 } 9 10 @Test 11 public void testHelloWorld_InstanceFactory() { 12 13 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 14 15 HelloWorld hello = (HelloWorld)context.getBean("helloWorld3"); 16 hello.hello(); 17 }
github地址:https://github.com/leechenxiang/maven-spring001-helloworld