浅析对Spring aware接口理解

2022-11-13 16:11:50 接口 理解 浅析

1. aware接口的作用

通过aware接口可以获取spring容器相关信息,但这样会与Spring容器耦合。

2. 常用aware接口及作用

执行顺序从上到下。

类名作用
BeanNameAware获得容器中bean名称
BeanClassLoaderAware获得类加载器
BeanFactoryAware获得bean创建工厂
EnvironmentAware获得环境变量
EmbeddedValueResolverAware获取spring容器加载的properties文件属性值
ResourceLoaderAware获得资源加载器
ApplicationEventPublisherAware获得应用事件发布器
MessageSourceAware获得文本信息
ApplicationContextAware获得当前应用上下文

3. 使用样例:ApplicationContextAware 在Bean中获取上下文



@Component("springUtil")
public final class SpringUtil implements ApplicationContextAware {
    
    private static ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) {
        synchronized (SpringUtil.class) {
            if (null == SpringUtil.applicationContext) {
                SpringUtil.applicationContext = applicationContext;
            }
        }
    }

    
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    private static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

4. 自定义aware的方式

先定义一个继承Aware的接口,然后注册一个实现BeanPostProcessor接口的Bean,在postProcessBeforeInitialization中处理Aware接口的逻辑。

举一个例子。获取调用自定义Aware接口方法的时间。

4.1 定义继承Aware的接口

public interface TimeAware extends Aware {
    void setTriggerTime(Date date);
}

4.2 注册实现BeanPostProcessor接口的Bean

@Component
public class AwarePostProcessor implements BeanPostProcessor {
    private final ConfigurableApplicationContext applicationContext;
    
    public AwarePostProcessor(ConfigurableApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Aware) {
            if (bean instanceof TimeAware) {
                // 实现自定义Aware接口的逻辑,设置调用的时间
                ((TimeAware)bean).setTriggerTime(new Date());
            }
        }
        return bean;
    }
}

4.3 实现TimeAware接口,并测试

@Import(AwarePostProcessor.class)
public class Test implements TimeAware {
    Date date;
    @Override
    public void setTriggerTime(Date date) {
        this.date = date;
    }

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(Test.class);
        Test bean = context.getBean(Test.class);
        System.out.println(bean.date);
    }
}

结果:

在这里插入图片描述

5. 源码处理方式

  • Bean实例化->填充属性->初始化,在初始化阶段将实现aware接口的Bean的方法执行。

1.先执行实现了下面三个aware接口的方法

  • BeanNameAware
  • BeanClassLoaderAware
  • BeanFactoryAware

2.调用初始化方法

3.执行实现剩下aware接口的方法

5.1 初始化阶段的源码逻辑

AbstractAutowireCapableBeanFactory#initializeBean

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			
			// 此处会调用ApplicationContextAwareProcessor执行其他的aware方法.
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null),
					beanName, "Invocation of init method failed", ex);
		}
		if (mbd == null || !mbd.isSynthetic()) {
			
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}

5.2 实现前三个aware接口的处理

调用initializeBean =>invokeAwareMethods方法将前三个aware方法调用
AbstractAutowireCapableBeanFactory#invokeAwareMethods

private void invokeAwareMethods(String beanName, Object bean) {
		if (bean instanceof Aware) {
			if (bean instanceof BeanNameAware) {
				((BeanNameAware) bean).setBeanName(beanName);
			}
			if (bean instanceof BeanClassLoaderAware) {
				ClassLoader bcl = getBeanClassLoader();
				if (bcl != null) {
					((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
				}
			}
			if (bean instanceof BeanFactoryAware) {
				((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
			}
		}
	}

5.3 剩余实现aware接口的Bean的处理

调用initializeBean =>applyBeanPostProcessorsBeforeInitialization=>BeanPostProcessor.postProcessBeforeInitialization
进入ApplicationContextAwareProcessor#postProcessBeforeInitialization=>invokeAwareInterfaces

private void invokeAwareInterfaces(Object bean) {
		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) {
			((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
		}
	}

因此可以自定义aware接口,并且注册一个实现BeanPostProcessor的postProcessBeforeInitialization方法的Bean,处理调用aware方法时的处理逻辑。

相关文章