欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ApplicationContextAware的使用理解

程序员文章站 2022-07-14 16:05:09
...

想象这么一个场景,一个单例bean中依赖有原型bean我们怎么去注入?

spring中我了解的大致有两种方式,一种是@Lookup依赖查找,另一种就是实现ApplicationContextAware 


使用方法

@Service
@Scope("prototype")
public class UserService {
	
}
@Component
public class UserService2 implements ApplicationContextAware {
	private ApplicationContext context;
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.context = applicationContext;
	}

	public void test(){
		UserService service = context.getBean(UserService.class);
		System.out.println(service);
	}
}

为什么我们实现这个接口就能拿到ApplicationContext?

首先在spring容器启动的时候,有添加一个ApplicationContextAwareProcessor

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		
		// Configure the bean factory with context callbacks.
		// 在beanFactory中添加ApplicationContextAwareProcessor,如果自定义类中有实现ApplicationContextAware就能拿到ApplicationContext
		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
		
}

ApplicationContextAwareProcessor是BeanPostProcessor的实现在容器初始化过程中会执行所有的BeanPostProcessor

@Override
public void refresh() throws BeansException, IllegalStateException {
	// 前后代码就删掉了
	// Invoke factory processors registered as beans in the context.
	invokeBeanFactoryPostProcessors(beanFactory);

				
}

在ApplicationContextAwareProcessor有这么一段,如果一个bean是ApplicationContextAware的实现,就调用它的set方法传入spring context

private void invokeAwareInterfaces(Object bean) {
		
		if (bean instanceof ApplicationContextAware) {
			((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
		}
	}

 

相关标签: spring