跟我学Spring3 学习笔记二

//静态工厂方法
public class HelloApiStaticFactory {
	public static HelloApi newInstance(String msg){
		//返回需要的Bean实例
		return new HelloImpl(msg);
	}
}

 

<!-- 静态工厂方法 -->
	<bean id="helloFactory" class="com.HelloApiStaticFactory"
		factory-method="newInstance" >
		<constructor-arg index="0" value="Hello Spring Static Factory" />
	</bean>

 

@Test
	public void testHelloApiStaticFactory(){
		//静态工厂方法
		BeanFactory beanFactory = new ClassPathXmlApplicationContext("helloworld.xml");
		HelloApi bean =  beanFactory.getBean("helloFactory",HelloApi.class);
		bean.sayHello();
		
	}

 
 
 工厂方法:

//工厂方法
public class HelloApiFactory {
	public HelloApi newInstance(String msg){
		return new HelloImpl(msg);
	}
}

 

<!-- 工厂方法  使用这种方式不能指定class属性,此时必须使用factory-bean属性来指定工厂Bean-->
	<bean id="beanFactory" class="com.HelloApiFactory" /> 
	<bean id="helloFac" factory-bean="beanFactory" factory-method="newInstance">
		<constructor-arg index="0" value="Hello Spring Factory" />
	</bean>

 

@Test
public void testHelloApiFactory(){
	//工厂方法
	BeanFactory beanFactory = new ClassPathXmlApplicationContext("helloworld.xml");
	HelloApi bean =  beanFactory.getBean("helloFac",HelloApi.class);
	bean.sayHello();
		
}

 

你可能感兴趣的:(Spring3)