Spring事件发布与监听机制ApplicationEventPublisher,EventListener

1.发布事件,一个事件增加一个方法

public class SpringEventPublisher {
	/**
	 *  publish knowledge event
	 * @param event
	 */
	public static void publish(DataEvent event) {
		SpringContextUtil.getApplicationContext().publishEvent(event);
	}

}

DataEvent

@Data
@AllArgsConstructor
@ToString
public class DataEvent {

	private String id;

	private String name;
}

2.工具类获取ApplicationContext

@Slf4j
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext APPLICATION_CONTEXT;

    @Override
    public synchronized void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.APPLICATION_CONTEXT = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return SpringContextUtil.APPLICATION_CONTEXT;
    }

	public static <T> T getBean(Class<T> requiredType) {
    	try {
			return getApplicationContext().getBean(requiredType);
		} catch (Exception e) {
    		LOGGER.error("getBean error, requiredType={}", requiredType, e);
		}
    	return null;
	}
}

3.监听处理事件,@EventListener注解;@Async开启异步支持,防止监听器方法异常影响主流程。

@Slf4j
@Service
public class DataEventListener {
   @Autowired
   private DataEventHandler eventHandler;
   /**
    *  Receive data event
    * @param event
    */
   @Async
   @EventListener(DataEvent.class)
   public void onDataEvent(DataEvent event) {
      LOGGER.info("Receive Data event: {}", event);
      // 处理事件
      eventHandler.handle(event);
      
   }

总结

​ 使用事件监听与发布机制可以使核心业务和子业务进行解耦,方便后期扩展,多个监听器可以监听同一个事件。

引用

上一篇:Virbox Protector AAB 加固-兼容 Google Play 上架


下一篇:Spring配置说明,(alias别名,bean配置,import引用)