spring系列3-后置处理器

Spring对bean的赋值, 注入其它组件, 生命周期注解功能,@Async等等功能,在低层都是通过底层对BeanPostProcessor也就是后置处理器的支持实现的。下面看几个常见的后置处理器,具体的spring源码将在以后分析。

1.ApplicationContextAware

类实现了ApplicationContextAware接口,可以取得上下文ApplicationContex,用于自己业务操作。

public class A implements ApplicationContextAware{
	private ApplicationContext applicationContext;
	public A(){
	}
	@PostConstruct
	public void init(){
		System.out.println("....@PostConstruct........");
	}
	
	@PreDestroy
	public void destory(){
		System.out.println("....@PreDestroy......");
	}
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		//将applicationContext传进来,可以拿到
		System.out.println(".....applicationContext........");
		this.applicationContext = applicationContext;
	}
}

ApplicationContextAware对应的后置处理器是ApplicationContextAwareProcessor。我们稍微看下源码:

//在类的属性设置完成之后,调用
	public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
		AccessControlContext acc = null;
		//权限控制
		if (System.getSecurityManager() != null &&
				(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
						bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
						bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
			acc = this.applicationContext.getBeanFactory().getAccessControlContext();
		}

		if (acc != null) {
			AccessController.doPrivileged((PrivilegedAction) () -> {
				//核心
				invokeAwareInterfaces(bean);
				return null;
			}, acc);
		}
		else {
			//核心
			invokeAwareInterfaces(bean);
		}

		return bean;
	}
 
  
private void invokeAwareInterfaces(Object bean) {
		if (bean instanceof Aware) {
			if (bean instanceof EnvironmentAware) {
				((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
			}
			if (bean instanceof EmbeddedValueResolverAware) {
				((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
			}
			if (bean instanceof ResourceLoaderAware) {
				((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
			}
			if (bean instanceof ApplicationEventPublisherAware) {
				((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
			}
			if (bean instanceof MessageSourceAware) {
				((MessageSourceAware) bean).setMessageSource(this.applicationContext);
			}

			if (bean instanceof ApplicationContextAware) {
				//调用实现类的setApplicationContext方法
				//applicationContext是在构造该后置处理器时候传入的
				((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
			}
		}
	}

2.BeanValidationPostProcessor

BeanValidationPostProcessor用来做数据校验的,比如对加了@Validated类按照JSR提供的校验注解(比如@Null)进行校验。源码重点如下:

	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if (!this.afterInitialization) {
			//类初始化前进行校验
			doValidate(bean);
		}
		return bean;
	}
	
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if (this.afterInitialization) {
			//类初始化后进行校验
			doValidate(bean);
		}
		return bean;
	}

3.InitDestroyAnnotationBeanPostProcessor

后置处理器是对@PostConstruct, @PreDestroy进行处理。关键源码如下:

	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		//找到初始化方法比如,@PostConstruct注解的方法
		LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
		try {
			//通过反射注入
			metadata.invokeInitMethods(bean, beanName);
		}
		catch (InvocationTargetException ex) {
			throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
		}
		return bean;
	}
public void invokeInitMethods(Object target, String beanName) throws Throwable {
			Collection checkedInitMethods = this.checkedInitMethods;
			Collection initMethodsToIterate =
					(checkedInitMethods != null ? checkedInitMethods : this.initMethods);
			if (!initMethodsToIterate.isEmpty()) {
				for (LifecycleElement element : initMethodsToIterate) {
					if (logger.isTraceEnabled()) {
						logger.trace("Invoking init method on bean '" + beanName + "': " + element.getMethod());
					}
					//反射调用,target为目标对象bean
					element.invoke(target);
				}
			}
		}

你可能感兴趣的:(spring)