Spring - Spring Data REST - Prevent The Methods in Event Handlers Be Triggered Twice

本文介绍如何通过创建自定义注解配置上下文来防止应用事件在不同层次触发多次,具体步骤包括重写发布事件方法、移除默认多播事件调用,并设置自定义上下文到DispatcherServlet。
<span style="background-color: rgb(255, 255, 255);">To prevent the methods be triggered twice, we need to overwrite the </span><strong style="background-color: rgb(255, 255, 255);">publishEvent(ApplicationEvent event)</strong><span style="background-color: rgb(255, 255, 255);"> method, then remove the code below</span>
<span style="white-space:pre">	</span>this.getApplicationEventMulticaster().multicastEvent(event);
        if(this.parent != null) {
            this.parent.publishEvent(event);
        }
So, it need to create a customized AnnotationConfuigWebApplicationContext:
package com.siemens.ct.its.iam.deploy.configuration;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.util.Assert;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by z002x71p on 2015/9/23.
 */
public class MyAnnotationConfigWebApplicationContext extends AnnotationConfigWebApplicationContext {

    public void publishEvent(ApplicationEvent event) {
        Assert.notNull(event, "Event must not be null");
        if(this.logger.isTraceEnabled()) {
            this.logger.trace("Publishing event in " + this.getDisplayName() + ": " + event);
        }

        this.getApplicationEventMulticaster().multicastEvent(event);
    }

    ApplicationEventMulticaster getApplicationEventMulticaster() throws IllegalStateException {
        for(Class<?> clazz = this.getClass() ; clazz != Object.class ; clazz = clazz.getSuperclass()) {
            String className = clazz.getName();
            System.out.println(className);
            if(className.equals("org.springframework.context.support.AbstractApplicationContext")){
                try {
                    Method method = clazz.getDeclaredMethod("getApplicationEventMulticaster") ;
                    method.setAccessible(true);
                    return (ApplicationEventMulticaster) method.invoke(this);
                }catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e){
                    throw new RuntimeException(e);
                }
            }
        }
        return null;
    }
}
And set it into the DispacherServlet.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值