factorybean用法

纸上得来终觉浅

1.什么是factorybean?

factorybean是一个工厂类接口,用户可以通过实现该接口来定制实例化bean的逻辑

getObject():返回factorybean创建的bean实例

isSingleton():指定factorybean创建的bean实例的作用域

getObjectType():指所创建的bean实例的类型


2.factorybean的作用?

由上面可以发现,factorybean实际上把应该在bean配置文件中配置的信息,放在它的实现类中实现了,它起到了创建bean的作用。这样一来当有复杂的bean之间的关系的时候,就不用再在bean配置文件中配置了,可以在factorybean姐苦衷显式的写出。


3.下面一个例子:

public class phone {
	private String size;
	private String name;
	private String logo;
	public String getSize() {
		return size;
	}
	public void setSize(String size) {
		this.size = size;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getLogo() {
		return logo;
	}
	public void setLogo(String logo) {
		this.logo = logo;
	}
	@Override
	public String toString() {
		return "phone [size=" + size + ", name=" + name + ", logo=" + logo + "]";
	}
	
}
public class people {
private String name;
private phone phone;
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public phone getPhone() {
	return phone;
}
public void setPhone(phone phone) {
	this.phone = phone;
}
@Override
public String toString() {
	return "people [name=" + name + ", phone=" + phone + "]";
}
}
public class peopleFactoryBean implements FactoryBean<people>{

	private String phoneInfo;
	public String getPhoneInfo() {
		return phoneInfo;
	}
	public void setPhoneInfo(String phoneInfo) {
		this.phoneInfo = phoneInfo;
	}

	@Override
	public people getObject() throws Exception {
		people people = new people();
		phone phone = new phone();
		String info[] = phoneInfo.split(",");
		phone.setSize(info[0]);
		phone.setName(info[1]);
		phone.setLogo(info[2]);
		people.setPhone(phone);
		people.setName(info[3]);
		return people;
	}

	@Override
	public Class<?> getObjectType() {
		return phone.class;
	}

	@Override
	public boolean isSingleton() {
		return false;
	}
	
}
<bean id="people" class="com.roadArchitectWeb.dao.peopleFactoryBean">
<property name="phoneInfo" value="5.2,P7,huawei,majintao"></property>
</bean>
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		people people = (people)ctx.getBean("people");
		System.out.println("AnimalMain.main():"+people.toString());
输出结果:

AnimalMain.main():people [name=majintao, phone=phone [size=5.2, name=P7, logo=huawei]]

由上段代码可以看到,一些配置信息和bean之间的关系在peopleFactoryBean中已经实现了,这样省略了很多bean配置文件的配置,people这个bean和它所持有的phone都是在getobject中创建的。

注: 但是会有这样一个问题,如果有一天phone的属性增加一个字段,如果是一般的bean配置,只需要改phone类和配置文件即可,但在这里,就需要更改peopleFactoryBeab的代码,这在我看来是丧失了部分的灵活性,不过在确定类及其属性不会更改的情况下,factorybean确实是省略配置的好办法.

你可能感兴趣的:(bean,FactoryBean,factory)