Spring之实现FactorBean接口在Spring IOC容器中配置Bean

Spring中有两种类型的Bean,一种是普通Bean,另一种是工厂Bean即FactoryBean
工厂Bean和普通Bean不同,其返回的对象不是指定类的一个实例,其返回的是该工厂Bean的getObject方法

示例代码如下:

//先准备一个Address类
public class Address {
	
	private String city;
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public Address(String city) {
		super();
		this.city = city;
	}
	public Address() {
	}
	@Override
	public String toString() {
		return "Address [city=" + city + "]";
	}
}
//FactoryBean工厂Bean
public class AddressBeanFactory implements FactoryBean<Address>{
	private String city;
	
	public void setCity(String city) {
		this.city = city;
	}
	
	//FactoryBean返回的实例
	@Override
	public Address getObject() throws Exception {
		return new Address(this.city);
	}

	//FactoryBean返回的类型
	@Override
	public Class<?> getObjectType() {
		return Address.class;
	}
	
	//FactoryBean返回的实例是否为单例
	@Override
	public boolean isSingleton() {
		return true;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值