如何在EJB拦截器的生命周期事件方法中获取调用者名称

Bal*_*sky 8 java interceptor ejb-3.0

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

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");
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

我想获得调用此拦截器的EJB的名称.我该怎么做?

我试过ctx.getMethod().getDeclaringClass().getSimpleName(),但ctx.getMethod()回报率nullpostConstruct(-)predestroy(-)方法.

Mik*_*unu 4

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

之所以如此,是因为调用生命周期回调方法的不是您的 EJB,而是容器。

如果您对拦截器和它所属的 bean 之间的关联感兴趣,那么 ctx.getTarget() 方法不符合您的目的吗?