spring-ioc流程
1:将bean放到一个容器中
2:spring中的aware的子类规定好回调接口
public interface ApplicationContextAware extends Aware { void setApplicationContext(ApplicationContext applicationContext) throws BeansException; }
3:写一个接口,实现 ApplicationContextAware
@Component @Configuration public class WebApplicationContextAware implements ApplicationContextAware { @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("---- ApplicationContextAware ----"); } }
4:遍历容器中的每个bean与Aware比较
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) { ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext); } } }
当bean是 Aware 的实现类,则进行下一步处理。直到使用 bean 调用 对应的方法
WebApplicationContextAware 注入到ioc容器后,遍历容器中的bean的时候,判断该bean是否为Aware类型的,如果是,会用ioc容貌后期中的 webApplicationContextAware 调用 setApplicationContext 方法。。实现其他类型的Aware回调方式类似