package com.astute.sparrow.spring.ioc.test; public class B { public void output() { System.out.println("B.output"); } }
package com.astute.sparrow.spring.ioc.test; public class A { private B b; public A() { } public A(B b) { super(); this.b = b; } public B getB() { return b; } public void setB(B b) { this.b = b; } }
//创建Bean工厂 DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); //生成BeanDefinition AbstractBeanDefinition newA = new RootBeanDefinition(A.class); newA.setScope(BeanDefinition.SCOPE_SINGLETON); AbstractBeanDefinition newB = new RootBeanDefinition(B.class); newB.setScope(BeanDefinition.SCOPE_PROTOTYPE); //注册 factory.registerBeanDefinition("a", newA); factory.registerBeanDefinition("b", newB); //功过构造函数注入 ConstructorArgumentValues argValues = new ConstructorArgumentValues(); argValues.addIndexedArgumentValue(0, newB); newA.setConstructorArgumentValues(argValues); //通过Setter方式注入 MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue(new PropertyValue("b", newB)); newA.setPropertyValues(propertyValues); A a = (A) factory.getBean("a"); a.getB().output();