官网地址: 1.8.3. Customizing Instantiation Logic with a FactoryBean
概述
FactoryBean字面意思是工厂Bean。它就是起到一个工厂的作用。其getObject()方法可以生产另外一个对象,且生产的对象,也交由Spring容器管理。
通过FactoryBean的实现类,首字母小写,获得的是getObject返回的对象。在首字母小写前面加一个&符号,获得的是FactoryBean实例本身。
Spring提供了几个FactoryBean的实现类。用于在Spring的Bean中配置相应集合属性。
ListFactoryBean、MapFactoryBean、SetFactoryBean
示例代码
public class Computer {
private String type;
private String display;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDisplay() {
return display;
}
public void setDisplay(String display) {
this.display = display;
}
@Override
public String toString() {
return "Computer{" + "type='" + type + '\'' + ", display='" + display + '\'' + '}';
}
}
/**
* FactoryBean 的作用:通过ApplicationContext.getBean() 获取到的是Computer对象
* 如果要获取Machine本身,在获取是用 & + id
*
* @see ListFactoryBean
*
*/
public class Machine implements FactoryBean<Computer> {
@Override
public Computer getObject() throws Exception {
Computer computer = new Computer();
computer.setType("笔记本");
computer.setDisplay("三星");
return computer;
}
@Override
public Class<?> getObjectType() {
return null;
}
}
public class FactoryBeanDemo {
public static void main(String[] args) {
// 加载context.xml
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/context-factorybean.xml");
Computer computer = context.getBean("machine", Computer.class);
System.out.println(computer);
//如果要获取Machine Bean本身
Machine machine = context.getBean("&machine", Machine.class);
System.out.println(machine);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
<!-- bean definitions here -->
<bean id="machine" class="org.xharvard.ioc.factorybean.Machine"/>
</beans>