目录
InitializingBean
当我们阅读一些优秀的开源代码时,会经常见到InitializingBean的身影,Spring启动后,初始化Bean时,若该Bean实现InitialzingBean接口,会自动调用afterPropertiesSet()方法,完成一些用户自定义的初始化操作。
ApplicationContext
是spring继BeanFactory之外的另一个核心接口或容器,允许容器通过应用程序上下文环境创建、获取、管理bean。为应用程序提供配置的中央接口。比BeanFactory功能更加强大。
BeanPostProcessor
含义正如其字面意思,bean的后置处理器,当所有的bean初始化完之后,调用的接口。一个前置,一个后置,AOP就是基于此实现的。
public interface BeanPostProcessor { @Nullable default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Nullable default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } }
ApplicationListener
Spring为我们提供一套较完善的监听机制。
可以自定义事件, 需要继承 ApplicationEvent类。(监听者模式)
ApplicationListener通过范型区分(订阅)不同事件
示例代码
首先自定义事件
public class MyEvent extends ApplicationEvent { private Object body; public MyEvent(Object source, Object body) { super(source); this.body = body; } public Object getBody() { return body; } public void setBody(Object body) { this.body = body; } }
监听器
@Component public class MyListener implements ApplicationListener<MyEvent> { @Override public void onApplicationEvent(MyEvent event) { System.out.println(event.getBody()); } }
使用
applicationContext中的 publishEvent() 方法推送事件。
注意: spring4.2之后提供注解版@EventListener支持
ApplicationContextAware
当一个类实现了这个接口之后,这个类就可以方便的获得ApplicationContext对象,Spring发现某个Bean实现了ApplicationContextAware接口,Spring容器会在创建该Bean之后,自动调用该Bean的setApplicationContext(参数)方法,调用该方法时,会将容器本身ApplicationContext对象作为参数传递给该方法。
示例代码
@Component public class SpringContextHelper implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(@NonNull ApplicationContext context) { applicationContext = context; } public static <T> T getInstance(String beanName, Class<T> beanType) { return applicationContext.getBean(beanName, beanType); } public static <T> T getInstance(Class<T> bean) { return applicationContext.getBean(bean); } }