`
liuzhaomin
  • 浏览: 204833 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

ObjectFactoryCreatingFactoryBean

阅读更多

 

package com.astute.sparrow.spring.ioc.method_injection;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component("a")
public class A implements BeanFactoryAware {
	@Autowired
	@Qualifier("b")
	private B b;
	
	private BeanFactory factory;
	
	private ObjectFactory objectFactory;
	
	public void printB() {
		System.out.println(getB());
	}

	public void setObjectFactory(ObjectFactory objectFactory) {
		this.objectFactory = objectFactory;
	}

	public B getB() {
		//return (B) factory.getBean("b");
		return (B) objectFactory.getObject();
	}

	public void setB(B b) {
		this.b = b;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.factory = beanFactory;
	}

}

package com.astute.sparrow.spring.ioc.method_injection;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("b")
@Scope("prototype")
public class B {

}
 
<bean id="b" class="com.astute.sparrow.spring.ioc.method_injection.B" scope="prototype"/>
<bean id="bFactory" class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean">
	<property name="targetBeanName">
		<idref bean="b"/>
	</property>
</bean>
<bean id="a" class="com.astute.sparrow.spring.ioc.method_injection.A">
	<property name="objectFactory" ref="bFactory"/>
</bean>
 
public class TestObjectFactory {

	public static void main(String[] args) {
		BeanFactory factory = new XmlBeanFactory(new ClassPathResource(
				"com/astute/sparrow/spring/ioc/method_injection/spring-objectfactory.xml"));
		A a = (A) factory.getBean("a");
		a.printB();
		a.printB();
		a.printB();
		a.printB();
	}

}
 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics