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.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; public void printB() { System.out.println(getB()); } public B getB() { return (B) factory.getBean("b"); } public void setB(B b) { this.b = b; } //容器在实例化实现了BeanFactoryAware接口的Bean时,会自动将容器本身注入该Bean @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 { }
<?xml version="1.0" encoding="GBK"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="a" class="com.astute.sparrow.spring.ioc.method_injection.A"> </bean> <bean id="b" class="com.astute.sparrow.spring.ioc.method_injection.B" scope="prototype"/> </beans>
package com.astute.sparrow.spring.ioc.method_injection; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class TestBeanFactoryAware { public static void main(String[] args) { BeanFactory factory = new XmlBeanFactory(new ClassPathResource( "com/astute/sparrow/spring/ioc/method_injection/spring-beanfactoryaware.xml")); A a = (A) factory.getBean("a"); a.printB(); a.printB(); a.printB(); } }