从拦截器类中发射CDI事件

时间:2014-04-19 21:29:51

标签: ejb ejb-3.0 cdi

是否可以从拦截器中发射CDI事件? (使用Jboss 7.1.1)

例如,如果我有一个拦截器PerformanceLogInterceptor

@Interceptors({PerformanceLogInterceptor.class})
public class ProcessHandler extends HandlerBase {

。 。

它可以发起这样的事件:

public class PerformanceLogInterceptor {

    private Logger LOG = LoggerFactory.getLogger("PerformanceLog");

    @EJB
    PerformanceMonitor performanceMonitor;

    @Inject
    Event<ExceptionEvent> exceptionEvent;


    @AroundInvoke
    @AroundTimeout
    public Object performanceLog( InvocationContext invocationContext ) throws Exception {
        String methodName = invocationContext.getMethod().toString();
        long start = System.currentTimeMillis();
        try {
            return invocationContext.proceed();
        } catch( Exception e ) {
            LOG.warn( "During invocation of: {} exception occured: {}", methodName, Throwables.getRootCause(e).getMessage() );
            performanceMonitor.addException( methodName, e );

            Exception toSend;
            if(e instanceof EfsobExceptionInformation ){
                toSend = e;
            } else {
                LOG.debug("Wrapping exception");
                EfsobExceptionWrapper wrapped = new EfsobExceptionWrapper(e);
                toSend = wrapped;
            }

            if(exceptionEvent != null) {
                LOG.debug("sending exceptionEvent");
                exceptionEvent.fire(new ExceptionEventBuilder()
                                .setExceptionName(toSend)
                                .setEfsobExceptionType(toSend)
                                .setId(toSend)
                                .setStacktrace(toSend)
                                .build()
                );
            } else {
                LOG.debug("exceptionEvent was null");
            }

            LOG.debug("rethrowing");
            throw toSend;
        } finally {
            long total = System.currentTimeMillis() - start;
            performanceMonitor.addPerformanceMetrics(methodName, total);
        }
    }

}

注意:在上面的运行时,exceptionEvent为null。

1 个答案:

答案 0 :(得分:0)

我将它移动到上面引用的PerformanceMonitor bean的Async块中....然后它可以工作(WAT?)

@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class PerformanceMonitor {

    @Inject
    Event<ExceptionEvent> exceptionEvent;

    private Logger LOG = LoggerFactory.getLogger("PerformanceMonitor");

    @Asynchronous
    public void addException(String methodName, Exception e) {

        if(exceptionEvent != null) {
            LOG.debug("sending exceptionEvent");
            exceptionEvent.fire(new ExceptionEventBuilder()
                            .setExceptionName(e)
                            .setEfsobExceptionType(e)
                            .setId(e)
                            .setStacktrace(e)
                            .build()
            );
        } else {
            LOG.debug("exceptionEvent was null");
        }
    }
}