一、ApplicationContextAware接口
當一個類需要獲取ApplicationContext實例時,可以讓該類實現ApplicationContextAware接口。代碼展示如下:
public class Animal implements ApplicationContextAware, BeanNameAware{ private String beanName; private ApplicationContext applicationContext; public void setBeanName(String name) { this.beanName = name; } /** * @param applicationContext 該參數將由Spring容器自動賦值 */ public void setApplicationContext(ApplicationContext applicationContext)throws BeansException { this.applicationContext = applicationContext; } public void run(){ System.out.println(beanName); //發布自定義事件 AnimalEvent event = new AnimalEvent(this, "老虎"); applicationContext.publishEvent(event); } }
通過@Autowired注解可以自動裝配一些常用對象實例:
@Autowired private MessageSource messageSource; @Autowired private ResourceLoader resourceLoader; @Autowired private ApplicationContext applicationContext;
二、ApplicationEvent抽象類
當需要創建自定義事件時,可以新建一個繼承自ApplicationEvent抽象類的類。代碼展示如下:
/** * 自定義事件 */ public class AnimalEvent extends ApplicationEvent { private String name; public String getName() { return name; } /** * @param source 事件源對象 */ public AnimalEvent(Object source){ super(source); } public AnimalEvent(Object source, String name){ super(source); this.name = name; } }
三、ApplicationListener接口
當需要監聽自定義事件時,可以新建一個實現ApplicationListener接口的類,並將該類配置到Spring容器中。代碼展示如下:
/** * 自定義事件監聽器 */ public class CustomEventListener implements ApplicationListener { public void onApplicationEvent(ApplicationEvent event) { if(event instanceof AnimalEvent){ AnimalEvent animalEvent = (AnimalEvent)event; System.out.println("觸發自定義事件:Animal name is " + animalEvent.getName()); } } }
<!-- 自定義事件監聽器:Spring容器自動注冊它 --> <bean id="customEventListener" class="com.cjm.spring.CustomEventListener"/>
要發布自定義事件,需要調用ApplicationContext的publishEvent方法,具體用法請看Animal類的源碼。
四、BeanNameAware接口
當bean需要獲取自身在容器中的id/name時,可以實現BeanNameAware接口。
五、InitializingBean接口
當需要在bean的全部屬性設置成功后做些特殊的處理,可以讓該bean實現InitializingBean接口。 效果等同於bean的init-method屬性的使用或者@PostContsuct注解的使用。 三種方式的執行順序:先注解,然后執行InitializingBean接口中定義的方法,最后執行init-method屬性指定的方法。
六、DisposableBean接口 當需要在bean銷毀之前做些特殊的處理,可以讓該bean實現DisposableBean接口。 效果等同於bean的destroy-method屬性的使用或者@PreDestory注解的使用。 三種方式的執行順序:先注解,然后執行DisposableBean接口中定義的方法,最后執行destroy-method屬性指定的方法