使用编码方式创建和绑定Bean

 

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();

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值