如何在EJB拦截器的生命周期事件方法中获取调用者名称 [英] How to get the invoker name in EJB interceptor's lifecycle event method

查看:210
本文介绍了如何在EJB拦截器的生命周期事件方法中获取调用者名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Java EE 5.我为所有EJB编写了一个拦截器,它有三种记录方法:

I use Java EE 5. I wrote an interceptor for all EJBs with three methods for logging:

public class DefaultInterceptor {
    public static final String PREFIX = "!!!!!!!!!Interceptor:";

    @PostConstruct
    public void postConstruct(InvocationContext ctx) {
        try {
            System.out.println(PREFIX + " postConstruct");
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    @PreDestroy
    public void preDestroy(InvocationContext ctx) {
        try {
            System.out.println(PREFIX + " predestroy");
            System.out.println(PREFIX + "ctx.preceed=" + ctx.proceed());
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    @AroundInvoke
    public Object intercept(InvocationContext ctx) throws Exception {
        System.out.println(PREFIX + "method invocation '" + ctx.getMethod().getName() + "'");
        System.out.println(PREFIX + "parameters ='" + Arrays.deepToString(ctx.getParameters()) + "'");
        System.out.println(Arrays.deepToString(ctx.getContextData().keySet().toArray()));
        Object result = null;
        try {
            result = ctx.proceed();
            System.out.println(PREFIX + "Method result='" + result + "'");
            return result;
        } catch (Exception ex) {
            System.out.println(PREFIX + "Method exception ='" + ex.getMessage() + "'");
            throw ex;
        } finally {
            System.out.println(PREFIX + "Method finished");
        }
    }
} 

我想得到这个名字调用此拦截器的EJB。我该怎么办?

I want to get the name of EJB which called this interceptor. How can I do it?

我试过 ctx.getMethod()。getDeclaringClass()。getSimpleName()但是 ctx.getMethod() postConstruct( - ) null >和 predestroy( - )方法。

I tried ctx.getMethod().getDeclaringClass().getSimpleName() but ctx.getMethod() returns null in postConstruct(-) and predestroy(-) methods.

推荐答案

对于生命周期回调,ctx.getMethod()返回null。例如,这里记录了这一点: http://docs.oracle。 com / javaee / 5 / api / javax / interceptor / InvocationContext.html

For lifecycle callbacks ctx.getMethod() returns null. This is documented for example here: http://docs.oracle.com/javaee/5/api/javax/interceptor/InvocationContext.html

就是这样,因为它不是你的EJB,而是调用生命周期的容器回调方法。

That is so, because it is not your EJB, but container who calls lifecycle callback methods.

如果你对它所属的拦截器和bean之间的关联感兴趣,ctx.getTarget()方法不能满足你的需求吗?

If you are interested about association between interceptor and bean it belongs to, doesn't ctx.getTarget() method serve your purpose?

这篇关于如何在EJB拦截器的生命周期事件方法中获取调用者名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆