xml定义一个factory bean,对应的对象是UserFactoryBean
public static void main(String[] args) {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:META-INF\\bean-creation-context.xml");
User user3 = beanFactory.getBean("user-by-factoryBean", User.class);
System.out.println(user3);
<bean id="user-by-factoryBean" class="com.lhz.spring.bean.factory.UserFactoryBean"/>
public class UserFactoryBean implements FactoryBean<User> {
@Override
public User getObject() throws Exception {
User user = new User();
user.setId(3);
user.setName("lhz factoryBean");
return user;
}
@Override
public Class<?> getObjectType() {
return User.class;
}
}
追踪User user3 = beanFactory.getBean("user-by-factoryBean", User.class);创建过程
image.pngimage.png
进去AbstractBeanFactory,跳到断点处,进入子类AbstractAutowireCapableBeanFactory重写的getObjectForBeanInstance方法
image.png
再进去AbstractAutowireCapableBeanFactory,走到断点,最终还是调用父类AbstractBeanFactory的
getObjectForBeanInstance方法
image.png
进入
image.png
进入FactoryBeanRegistrySupport,
image.png
跳到这个类的doGetObjectFromFactoryBean方法
image.png这就是我们实现FactoryBean接口的实现方法,再返回这个对象
image.png
并放入缓存
image.png
网友评论