Spring源码-createBeanInstance方法Supplier创建bean实例

一、例子

Supplier.java

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

java8以后提供的接口,可以看作是生产者,返回一个对象。

User.java

public class User {
private Integer id;

private String name;


private Integer age;

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;
}

public Integer getAge() {
	return age;
}

public void setAge(Integer age) {
	this.age = age;
}

@Override
public String toString() {
	final StringBuffer sb = new StringBuffer("User{");
	sb.append("id=").append(id);
	sb.append(", name='").append(name).append('\'');
	sb.append(", age=").append(age);
	sb.append('}');
	return sb.toString();
}
}

SupplierBeanFactoryPostProcessor.java

public class SupplierBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
	AbstractBeanDefinition user = (AbstractBeanDefinition)beanFactory.getBeanDefinition("user");
	user.setInstanceSupplier(()->{
		User user1 = new User();
		return user1;
	});
}
}

supplier.xml

<?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="user" class="supplier.User">
		<property name="id" value="1"/>
		<property name="name" value="测试"/>
		<property name="age" value="20"/>
 	</bean>

	<bean class="supplier.SupplierBeanFactoryPostProcessor"/>
</beans>

Test.java

public class Test {
public static void main(String[] args) {
	ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("supplier.xml");

	User user = applicationContext.getBean(User.class);
	System.out.println(user);
}
}

二Spring源码解读Supplier创建bean实例

AbstractAutowireCapableBeanFactory的createBeanInstance:

  Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
	if (instanceSupplier != null) {
		return obtainFromSupplier(instanceSupplier, beanName);
	}

protected BeanWrapper obtainFromSupplier(Supplier<?> instanceSupplier, String beanName) {
	Object instance;

	String outerBean = this.currentlyCreatedBean.get();
	this.currentlyCreatedBean.set(beanName);
	try {
		instance = instanceSupplier.get();
	}
	finally {
		if (outerBean != null) {
			this.currentlyCreatedBean.set(outerBean);
		}
		else {
			this.currentlyCreatedBean.remove();
		}
	}

	if (instance == null) {
		instance = new NullBean();
	}
	BeanWrapper bw = new BeanWrapperImpl(instance);
	initBeanWrapper(bw);
	return bw;
}

如果AbstractBeanDefinition的instanceSupplier不为null,则调用instanceSupplier创建bean实例。

posted @ 2022-09-30 14:46  shigp1  阅读(160)  评论(0编辑  收藏  举报