Spring 中BeanFactoryPostProcessor和BeanPostProcessor接口的分析

本文分析了Spring中的BeanFactoryPostProcessor和BeanPostProcessor接口。BeanFactoryPostProcessor在bean实例化前对bean定义进行修改,如改变bean的scope。BeanPostProcessor则在bean实例化、配置及初始化前后插入自定义逻辑,通过Ordered接口控制执行顺序。通过实例展示了它们在实际应用中的作用。

一、BeanFactoryPostProcessor是在spring加载了bean定义文件之后,bean实例化之前执行的。

       该接口只有一个postProcessBeanFactory方法,这个方法的入参是这个类型ConfigurableListableBeanFactory,该类型的定义如下:

public interface ConfigurableListableBeanFactory
		extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory {
	
	void ignoreDependencyType(Class<?> type);
	
	void ignoreDependencyInterface(Class<?> ifc);

	void registerResolvableDependency(Class<?> dependencyType, @Nullable Object autowiredValue);

	boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor)
			throws NoSuchBeanDefinitionException;

	BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
	
	Iterator<String> getBeanNamesIterator();
	
	void clearMetadataCache();

	void freezeConfiguration();

	boolean isConfigurationFrozen();

	void preInstantiateSingletons() throws BeansException;

}

可以看到里面有个getBeanDefinition的方法,然后我们就可以对里面的定义进行修改,该类定义如下:


public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {

	String SCOPE_SINGLETON = ConfigurableBeanFactory.SCOPE_SINGLETON;

	String SCOPE_PROTOTYPE = ConfigurableBeanFactory.SCOPE_PROTOTYPE;

	int ROLE_APPLICATION = 0;
	
	int ROLE_SUPPORT = 1;
	
	int ROLE_INFRASTRUCTURE = 2;
	
	void setParentName(@Nullable String parentName);
	
	@Nullable
	String getParentName();
	
	void setBeanClassName(@Nullable String beanClassName);
	
	@Nullable
	String getBeanClassName();
	
	void setScope(@Nullable String scope);
	
	@Nullable
	String getScope();
	
	void setLazyInit(boolean lazyInit);
	
	boolean isLazyInit();
	
	void setDependsOn(@Nullable String... dependsOn);
	
	@Nullable
	String[] getDependsOn();
	
	void setAutowireCandidate(boolean autowireCandidate);
	
	boolean isAutowireCandidate();
	
	void setPrimary(boolean primary);
	
	boolean isPrimary();

	void setFactoryBeanName(@Nullable String factoryBeanName);

	@Nullable
	String getFactoryBeanName();
	
	void setFactoryMethodName(@Nullable String factoryMethodName);
	
	@Nullable
	String getFactoryMethodName();

	ConstructorArgumentValues getConstructorArgumentValues();

	default boolean hasConstructorArgumentValues() {
		return !getConstructorArgumentValues().isEmpty();
	}
	
	MutablePropertyValues getPropertyValues();

	default boolean hasPropertyValues() {
		return !getPropertyValues().isEmpty();
	}
	
	void setInitMethodName(@Nullable String initMethodName);
	
	@Nullable
	String getInitMethodName();
	
	void setDestroyMethodName(@Nullable String destroyMethodName);

	@Nullable
	String getDestroyMethodName();
	
	void setRole(int role);
	
	int getRole();
	
	void setDescription(@Nullable String description);
	
	@Nullable
	String getDescription();
	
	ResolvableType getResolvableType();
	
	boolean isSingleton();

	boolean isPrototype();

	boolean isAbstract();

	@Nullable
	String getResourceDescription();

	@Nullable
	BeanDefinition getOriginatingBeanDefinition();

}

例如:我们修改一个bean 属性的scope该字段,从singleton(单例)修改为prototype(多例)

修改前:

spring-config.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 https://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<bean id="userService" class="lsq.service.impl.UserServiceImpl" scope="singleton"></bean>
</beans>
UserService
public interface UserService {
	public String print(String param);
}
UserServiceImpl
public class UserServiceImpl implements UserService {
	@Override
	public String print(String param) {
		return "hello" + param;
	}
}
TestApplication
public class TestApplication {

	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath*:spring-config.xml");
		UserService userService = (UserService) applicationContext.getBean("userService");
		System.out.println(userService);
		UserService userService1 = (UserService) applicationContext.getBean("userService");
		System.out.println(userService1);
	}
}

输出结果为:

lsq.service.impl.UserServiceImpl@667a738
lsq.service.impl.UserServiceImpl@667a738

修改后:

在spring-config.xml中加入下面一段代码:

<bean id="myBeanPostProcessor" class="lsq.config.MyBeanFactoryPostProcessor" />

然后添加下面代码:

MyBeanFactoryPostProcessor
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		BeanDefinition beanDefinition = beanFactory.getBeanDefinition("userService");
		beanDefinition.setScope("prototype");
	}
}

输出结果:

lsq.service.impl.UserServiceImpl@55040f2f
lsq.service.impl.UserServiceImpl@64c87930

发现确实是从单例改成多例了,还可以修改构造函数注入的属性值

<bean id="orderService" class="lsq.service.impl.OrderServiceImpl">
   <constructor-arg name="orderId" value="123"></constructor-arg>
</bean>

在postProcessBeanFactory中添加如下代码即可:

BeanDefinition beanDefinition = beanFactory.getBeanDefinition("orderService");
PropertyValue propertyValue = new PropertyValue("orderId", "456");
beanDefinition.getPropertyValues().addPropertyValue(propertyValue);

 

二、BeanPostProcessor要在bean实例化、配置以及其他初始化方法前后要添加一些自己逻辑处理。该接口可以被实现一次或者多次,然后通过实现Ordered接口的getOrder方法来指定执行的先后顺序。

该接口有postProcessBeforeInitialization和postProcessAfterInitialization这两个方法:

1、postProcessBeforeInitialization:该方法会在bean实例化之后、依赖注入之后和自定义方法之前执行(bean标签里面指定的init-method或者该bean实现了该接口InitializingBean)

2、postProcessAfterInitialization:该方法会在bean实例化之后、依赖注入之后和自定义方法之后执行

下面我们做下测试:

在spring-config.xml中加入下面一段代码:

<bean id="myBeanPostProcessor" class="lsq.config.MyBeanPostProcessor" />
<bean id="myBean" class="lsq.bean.MyBean" init-method="init">
		<property name="name" value="lsq"></property>
</bean>
MyBeanPostProcessor
public class MyBeanPostProcessor implements BeanPostProcessor {
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("----调用MyBeanPostProcessor的postProcessBeforeInitialization方法----");
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("----调用MyBeanPostProcessor的postProcessAfterInitialization方法----");
		return bean;
	}
}

MyBean

public class MyBean implements InitializingBean {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		System.out.println("调用setName方法:" + name);
		this.name = name;
	}

	public MyBean(){
		System.out.println("调用MyBean构造函数");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("调用afterPropertiesSet方法");
	}

	public void init(){
		System.out.println("调用init方法");
	}
}
MyBeanFactoryPostProcessor
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		System.out.println("----调用BeanFactoryPostProcessor的postProcessBeanFactory方法----");
	}
}
TestApplication
public class TestApplication {

	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath*:spring-config.xml");
		MyBean myBean = (MyBean) applicationContext.getBean("myBean");
		System.out.println(myBean.getName());
	}
}

输出结果:

----调用BeanFactoryPostProcessor的postProcessBeanFactory方法----
调用MyBean构造函数
调用setName方法:lsq
----调用MyBeanPostProcessor的postProcessBeforeInitialization方法----
调用afterPropertiesSet方法
调用init方法
----调用MyBeanPostProcessor的postProcessAfterInitialization方法----
lsq

综上可知:

在bean实例化之前,首先执行实现该接口BeanFactoryPostProcessor的postProcessBeanFactory方法,然后通过调用bean的无参构造函数实例化bean,并调用set方法注入属性值。bean实例化之后,先调用实现该接口BeanPostProcessor的postProcessBeforeInitialization方法,如果该bean实现了接口InitializingBean,会先调用其afterPropertiesSet方法,然后在执行init-method,最后再执行实现该接口BeanPostProcessor的postProcessAfterInitialization方法。

如有分析不对的地方,欢迎各位大佬指正,谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值