Spring后置处理器BeanPostProcessor

  1. 概述
    BeanPostProcessor[interface]是spring的后置处理器,在bean初始化前后进行一些初始化工作。
    postProcessBeforeInitialization在初始化之前工作
    postProcessAfterInitialization在初始化之后工作
  2. Spring底层对BeanPostProcessor的使用
    ApplicationContextAwareProcessor中使用

    在spring类中需要使用到spring的上下文(ApplicationContext),只需要实现ApplicationContextAware,后置处理器会自动赋值
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    		if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
    				bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
    				bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){
    			return bean;
    		}
    
    		AccessControlContext acc = null;
    
    		if (System.getSecurityManager() != null) {
    			acc = this.applicationContext.getBeanFactory().getAccessControlContext();
    		}
    
    		if (acc != null) {
    			AccessController.doPrivileged((PrivilegedAction) () -> {
    				invokeAwareInterfaces(bean);
    				return null;
    			}, acc);
    		}
    		else {
    			invokeAwareInterfaces(bean);
    		}
    
    		return bean;
    	}   
    AutowiredAnnotationBeanPostProcessor自动装配中使用
    
    





     

    你可能感兴趣的:(spring,java,后端)