Spring中使用静态工厂方法创建bean

当使用静态工厂方法创建bean实例的时候,class属性也必须指定,但是此时class属性并不是指定bean实例的实现类,而是静态工厂类,spring需要知道由哪个静态工厂方法来创建bean
除此之外还需要使用factory-method属性来指定静态工厂方法名,spring将调用静态工厂方法来返回一个bean实例,一旦获得了指定的bean实例,spring后面的处理步骤和采用普通方法创建bean实例完全一样
下面贴出我的代码
Being.java

package staticbean;
public interface Being {
	public void testBeing();
}

Dog.java

package staticbean;

public class Dog implements Being {

	private String msg;

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

	@Override
	public void testBeing() {
		// TODO Auto-generated method stub
		System.out.println(msg + "    爱吃骨头");
	}

}

Cat.java

package staticbean;

public class Cat implements Being {
	private String msg;

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

	@Override
	public void testBeing() {
		// TODO Auto-generated method stub
		System.out.println(msg + "    猫爱吃老鼠");
	}

}

BeingFactory.java

package staticbean;

public class BeingFactory {
	public static Being getBeing(String arg) {
		if (arg.equalsIgnoreCase("dog")) {
			return new Dog();

		} else {
			return new Cat();
		}
	}
}

SpringTest.java

package staticbean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {
	public static void main(String[] args) {
			ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
			Being b1 = ctx.getBean("dog",Being.class);
			b1.testBeing();
			Being b2 = ctx.getBean("cat",Being.class);
			b2.testBeing();
	}
}

然后是bean.xml

<bean id="dog" class="staticbean.BeingFactory" factory-method="getBeing">
		<!-- 配置静态工厂方法的参数 -->
		<constructor-arg value="dog"></constructor-arg>
		<property name="msg" value="我是狗"></property>
	</bean>
	<bean id="cat" class="staticbean.BeingFactory" factory-method="getBeing">
		<constructor-arg value="cat"></constructor-arg>
		<property name="msg" value="我是猫"></property>
	</bean>

发表评论

电子邮件地址不会被公开。 必填项已用*标注