Aware 接口用于注入一些与容器相关信息
示例
启动类:
public class A06 {
public static void main(String[] args) {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBean("myBean", MyBean.class);
context.refresh(); // 1. beanFactory 后处理器, 2. 添加 bean 后处理器, 3. 初始化单例
context.close();
}
}
@Slf4j
public class MyBean implements BeanNameAware, ApplicationContextAware, BeanFactoryAware {
@Override
public void setBeanName(String name) {
log.debug("当前bean " + this + " 名字叫:" + name);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
log.debug("当前bean " + this + " ApplicationContext容器是:" + applicationContext);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
log.debug("当前bean " + this + " BeanFactory容器是:" + beanFactory);
}
}
输出结果:
[DEBUG] 20:32:48.292 [main] com.xc.a06.MyBean - 当前bean com.xc.a06.MyBean@401e7803 名字叫:myBean
[DEBUG] 20:32:48.310 [main] com.xc.a06.MyBean - 当前bean com.xc.a06.MyBean@401e7803 BeanFactory容器是:org.springframework.beans.factory.support.DefaultListableBeanFactory@548ad73b: defining beans [myBean]; root of factory hierarchy
[DEBUG] 20:32:48.310 [main] com.xc.a06.MyBean - 当前bean com.xc.a06.MyBean@401e7803 ApplicationContext容器是:org.springframework.context.support.GenericApplicationContext@12843fce, started on Fri Aug 05 20:32:48 CST 2022
Process finished with exit code 0