spring 容器的自帶事件以及 自定義事件
阿新 • • 發佈:2018-11-19
ApplicationEvent
spring 的事件是為bean與bean 之間的訊息通訊提供了支援,當一個bean 處理完一個任務後,希望另外一個bean 知道並能夠做出相應的處理,這時需要另外一個bean監聽當前bean 所傳送的事件。
ApplicationEvent以及Listener是Spring為我們提供的一個事件監聽、訂閱的實現,內部實現原理是觀察者設計模式,設計初衷也是為了系統業務邏輯之間的解耦,提高可擴充套件性以及可維護性。事件釋出者並不需要考慮誰去監聽,監聽具體的實現內容是什麼,釋出者的工作只是為了釋出事件而已。
ApplicationEvent 可以對多種事件進行監聽,下面是一些簡單的事件監聽
@Component public class ApplicationConfig implements ApplicationListener<ApplicationEvent> { private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationConfig.class); @Override public void onApplicationEvent(ApplicationEvent applicationEvent) { if (applicationEvent instanceof ContextStartedEvent) { LOGGER.info("spring happen start work"); } else if (applicationEvent instanceof ContextRefreshedEvent) { //一般來說,可以使用ContextRefreshedEvent 在程式啟動的時候執行一些需要程式執行的方法,例如文字的讀取等 if (((ContextRefreshedEvent) applicationEvent).getApplicationContext().getParent() == null) { LOGGER.info("spring happen refresh event "); } } else if (applicationEvent instanceof ContextStoppedEvent) { LOGGER.info("spring happen stop event "); } else if (applicationEvent instanceof ContextClosedEvent) { LOGGER.info("spring happen close event "); } else { LOGGER.info("spring happen other event " + applicationEvent.getClass().getSimpleName()); } } }
ContextRefreshedEvent 事件需要特別注意,他可以支援在程式啟動的時候執行需要執行的方法
自定義事件
spring 的事件需要遵循以下流程
- 繼承ApplicationEvent 實現自定義事件
/** * Created by Sean on 2018/7/19 * * @author Sean */ public class UserEvent extends ApplicationEvent { private String msg; public UserEvent(Object source ,String msg) { super(source); this.msg=msg; } public String getMsg() { return msg; } }
- 定義事件監聽器 實現applicationListener
(1.實現applicationListener ,並指定監聽事件的型別- 使用onapplicationevent 方法對訊息進行接收處理 )
/**
* Created by Sean on 2018/7/19
*
* @author Sean
*/
@Component
public class UserEventListener implements ApplicationListener<UserEvent> {
private static final Logger LOGGER= LoggerFactory.getLogger(UserEventListener.class);
@Override
public void onApplicationEvent(UserEvent userEvent) {
String msg = userEvent.getMsg();
LOGGER.info("User Event Listener get Msg form UserEvent is "+msg);
}
}
- 使用容器釋出事件
1.注入 applicationcontext 來發布事件
2.使用applicationcontext的publishevent 方法來發布事件
@Component
public class UserEventPublisher {
@Autowired
private ApplicationContext applicationContext;
public void publish(String msg){
applicationContext.publishEvent(new UserEvent(this,msg));
}
}
- 釋出事件
@RestController
public class UserEventController {
@Autowired
private UserEventPublisher userEventPublisher;
@RequestMapping("publish")
public String publish(){
userEventPublisher.publish("hello user");
return "publish event";
}
}
github url:springbootcustomerevent