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();
return b;
}
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="a" class="com.astute.sparrow.spring.ioc.method_injection.A"> <property name="b" ref="b"/> <replaced-method name="printB" replacer="aMethodReplacer"/> </bean> <bean id="aMethodReplacer" class="com.astute.sparrow.spring.ioc.method_injection.AMethodReplacer"/>
BeanFactory factory = new XmlBeanFactory(new ClassPathResource(
"com/astute/sparrow/spring/ioc/method_injection/spring-methodreplacer.xml"));
A a = (A) factory.getBean("a");
a.printB();
a.printB();
a.printB();
输出:
写道
wo do nothing this time...
wo do nothing this time...
wo do nothing this time...
wo do nothing this time...
wo do nothing this time...