牧场SZShepherd 2020-02-23
首先看一个例子,例子内容延续上一篇ApplicationContextAware的使用:
package com.springinit; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanNameAware; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringInit implements ApplicationContextAware, BeanNameAware { public static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("spring init"); context = applicationContext; } @Override public void setBeanName(String name) { System.out.println("BeanNameAware:" + name); } }
启动一个spring容器后的打印结果为:
BeanNameAware:springInit
spring init
由此可得出如下结论:
另外:除了上述两个Aware后缀的接口外,spring还提供了其他的生命周期的aware接口,比如:BeanFactoryAware、BeanClassLoaderAware等,在某些bean的业务逻辑中若需要用到spring容器的这些属性,可以采用实现Aware后缀的接口来获取,用的最多还是ApplicationContextAware来获取ApplicationContext。