Interceptor不是从同一EJB中的另一个EJB方法触发的

Str*_*der 4 java ejb java-ee interceptor

脚本

两个方法在同一个EJB中使用2x相同的Interceptor:

...
 @Interceptors(PerformanceAuditor.class)
public Date refreshIfNecessary() {
    // there is also the PerformanceAuditor-Interceptor on this method
    Pair<Date,String> lastImportDate = importDbDAO.findLatestImportLog();

    someContainer.reloadIfNecessary(lastImportDate);
    return lastImportDate.getLeft();
}

@Interceptors(PerformanceAuditor.class)
public boolean checkAndRefreshIfNecessary(final Date importDate) {
    Date lastImportDate = refreshIfNecessary();
    return lastImportDate.after(importDate);
}
...
Run Code Online (Sandbox Code Playgroud)

现在我们使用以下结果在外部调用此EJB方法:

  • 调用refreshIfNecessary() - > PerformanceAuditor被调用2次
  • 调用checkAndRefreshIfNecessary() - >还调用了PerformanceAuditor 2次!(但是从一个嵌套级别开始预计会有3次!)

那么这里发生了什么?

Str*_*der 9

答案很简单:

拦截器仅在被称为"EJB调用"(即通过其EJB接口)时才"触发".但在checkAndRefreshIfNecessary()的调用checkAndRefreshIfNecessary()是一个简单的Java方法调用,以不被容器注意.

解决方案:要在EJB内部调用EJB中的方法作为EJB调用,您必须通过其接口进行访问,例如通过注入的SessionContext然后通过context.getEJBLocalObject()来访问 ...但这肯定不是一个很好的解决方案!在这种情况下,更好地重新考虑您的设计!

PS:这是一个很好的例子,人们仍然需要了解应用服务器的内部.不幸的是,从EJB3开始,大多数功能都非常容易使用,以至于越来越多的开发人员不会遇到内部因素,这会更频繁地导致此类错误或至少是糟糕的设计......