BeanFactory 是 IoC 底层容器;FactoryBean 是 创建 Bean 的一种方式,帮助实现复杂的初始化逻辑。
看个例子:
User.java
package constxiong;
public class User {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
UserFactoryBean 实现 FactoryBean 接口
package constxiong;
import org.springframework.beans.factory.FactoryBean;
/**
* UserFactoryBean 实现 FactoryBean 接口,用于构造 User 的bean
* @author ConstXiong
*/
public class UserFactoryBean implements FactoryBean<User> {
@Override
public User getObject() throws Exception {
User user = new User();
user.setId(2);
user.setName("customUser");
return user;
}
@Override
public Class<?> getObjectType() {
return User.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
spring 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="constxiong" class="constxiong.User">
<property name="id" value="1"/>
<property name="name" value="constxiong"/>
</bean>
<bean id="customUser" class="constxiong.UserFactoryBean"></bean>
</beans>
测试代码
package constxiong;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
/**
* 测试 BeanFactory 与 FactoryBean 的区别
* @author ConstXiong
*/
public class Test {
public static void main(String[] args) {
String xmlPath = "META-INF/spring-beanfactory-factorybean.xml";
getBeanByBeanFactory(xmlPath);
}
/**
* 通过 DefaultListableBeanFactory 获取 bean
*/
private static void getBeanByBeanFactory(String xmlPath) {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(beanFactory);
xmlReader.loadBeanDefinitions(xmlPath);
User user = beanFactory.getBean("constxiong", User.class);
System.out.println(user);
user = beanFactory.getBean("customUser", User.class);
System.out.println(user);
// 获取 UserFactoryBean 本身
UserFactoryBean userFactoryBean = beanFactory.getBean("&customUser", UserFactoryBean.class);
System.out.println(userFactoryBean);
}
}
说明:
ConstXiong 备案号:苏ICP备16009629号-3