为什么我的拦截器类不能使用调度方法?

时间:2017-10-21 23:17:12

标签: java interceptor ejb-3.1

我的WildFly 10.2.0服务器上有很多Stateless个bean。每次我尝试使用@Interceptors({LogService.class})时,它都适用于任何方法,除了Stateless只有2 @Schedule(second = "*/2", minute = "*", hour = "*")个方法的bean。我找了文档,但没有发现任何线索。谁能帮我?我正在使用Java 8。

这是我的拦截器类:

public class LogService {

@AroundInvoke
public Object interceptsAngLog(InvocationContext context) throws Exception {

    Long millis = System.currentTimeMillis();
    LocalTime now = new LocalTime();

    Object object = context.proceed();

    String method = context.getMethod().getName();
    String className = context.getTarget().getClass().getName();
    Long millisSpent = System.currentTimeMillis() - millis;

    System.out.println("[LOG] " + now.toString() + "-" + className + "-" + method + ": " + millisSpent);

    return object;
}
}

这是我的日程安排课程:

@Stateless
@Interceptors({LogService.class})
public class ScoreTimerService {

@EJB
private AccountDao accountDao;

@Schedule(second = "*/3", minute = "*", hour = "*")
public void addPointsDueOnlineState() {
    List<Account> list = accountDao.findOnline();
    for (Account account : list) {
        account.addScore(5);
        accountDao.update(account);
    }
}

@Schedule(second = "*/2", minute = "*", hour = "*")
public void removePointsDueTime() {
    List<Account> list = accountDao.findAll();
    for (Account account : list) {
        account.removeScore(1);
        accountDao.update(account);
    }
}

}

我尝试在课堂上使用on方法替换@Interceptors({LogService.class}) @Interceptors(LogService.class),但没有一种方法有效。

1 个答案:

答案 0 :(得分:1)

我发现只有@AroundTimeout符号可以与@Schedule EJB Bean一起使用。所以我添加了这样的方法:

@AroundInvoke
public Object intercept(InvocationContext context) throws Exception {
    return monitor(context);
}

@AroundTimeout
public Object interceptSchedule(InvocationContext context) throws Exception {
    return monitor(context);
}

private Object monitor(InvocationContext context) throws Exception {
    long millis = System.currentTimeMillis();

    String method = context.getMethod().getName();
    String className = context.getTarget().getClass().getSimpleName();

    Object object = context.proceed();

    long newMillis = System.currentTimeMillis() - millis;
    System.out.println("[LOG]-" + method + "." + className + "-" + newMillis + "ms");
    return object;
}

对于@Schedule和非@Schedule bean而言,它就像一个魅力