首页 > 编程语言 > 详细

Spring 学习总结 使用静态工厂创建Bean

时间:2016-06-21 20:41:00      阅读:296      评论:0      收藏:0      [点我收藏+]

创建Bean时,class属性必须指定,此时为静态工厂类。 factory-method指定静态工厂方法名。

接口:

public interface Being {
	public void testBeing();
}

Dog类

public class Dog implements Being{
	
	private String msg;

	public void setMsg(String msg) {
		this.msg = msg;
	}

	@Override
	public void testBeing() {
		System.out.println(msg + " 狗爱啃骨头");
		
	}

}

 

Cat类

public class Cat implements Being{

	private String msg;

	public void setMsg(String msg) {
		this.msg = msg;
	}

	@Override
	public void testBeing() {
		System.out.println(msg + " 猫爱吃老鼠!");
		
	}

}

 

Bean里配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<bean id="dog" class="com.springtest2.factory.BeingFactory"
		factory-method="getBeing">
		<constructor-arg value="dog" />
		<property name="msg" value="我是狗" />
	</bean>

	<bean id="cat" class="com.springtest2.factory.BeingFactory"
		factory-method="getBeing">
		<constructor-arg value="cat" />
		<property name="msg" value="我是猫" />
	</bean>

</beans>

 调用测试

	private static void testFactory(){
		ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"beans_factory.xml"});
		Being b1 = context.getBean("dog", Being.class);
		b1.testBeing();
		
		Being b2 = context.getBean("cat", Being.class);
		b2.testBeing();
	}

输出结果

技术分享

 

Spring 学习总结 使用静态工厂创建Bean

原文:http://www.cnblogs.com/linlf03/p/5604878.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!