后端Java线程中的AspectJ

问题描述 投票:0回答:1

我有一个后端线程,我在 JBoss Mbeans 的 start 方法中创建了它:

public interface HScannerServiceMBean {
  public void create();
  public void start();
  public void stop();
  public void destroy();
  public boolean isMasterNode();
  public void startSingleton(); 
  public void stopSingleton();
}
public class HScannerService implements HScannerServiceMBean {
  public void create() {
    log.info("Creating Service.......................................");
  }

  public void start() {
    log.info("Starting Service.......................................");
    TestThread tt;
    try {
      tt = new TestThread(1);
      tt.startThread();
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }
}
public class TestThread implements Runnable {
  private boolean running = false;
  int mThreadName;

  private Thread thread;

  protected TestThread(int pThreadName) throws NamingException {
    mThreadName = pThreadName;
    this.thread = new Thread(this);
    this.thread.setDaemon(true);
    this.thread.setPriority(Thread.MIN_PRIORITY);
  }

  public void startThread() {
    if (!this.running) {
      this.running = true;
      this.thread.start();
    } else {
      log.info("Thread already running");
    }
  }

  public void run() {
    System.out.println("Thread run method");
    throw new NumberFormatException("incorrect number");
  }

  public void terminate() {
    setRunning(false);
  }

  public boolean isRunning() {
    return running;
  }

  public void setRunning(boolean running) {
    this.running = running;
  }
}

我在pom.xml中添加了AspectJ:

<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjrt</artifactId>
  <version>1.7.4</version>
</dependency>
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.8.9</version>
</dependency>

我的方面类看起来像这样:

@Aspect
public class ExceptionTranslationAspect {
  @AfterThrowing(pointcut = "execution(* com.ent.service..*(..)) || execution(* com.ent.domain..*(..))", throwing = "ex")
  public void logAfterThrowingExceptionCall(Exception ex) throws Throwable {
    System.out.println("****exception received!");
  }
}

线程抛出一个简单的异常,该异常应该被这个方面捕获并打印“****收到异常!”。但方面方法没有被调用。我的问题是,我们可以将 AspectJ 与后端线程一起使用吗?如果是,我的代码有什么问题?

我正在使用 JDK 8 和 Wildfly 16。

multithreading aop aspectj java-threads mbeans
1个回答
0
投票

将 AspectJ 库添加到 POM 不会激活 AspectJ。您需要通过

-javaagent:/path/to/aspectweaver.jar
或通过在 WildFly 中配置代理的其他方式(如果有)来使用加载时编织。或者您可以使用 AspectJ Maven 插件进行编译时编织。

此外,在同一个 POM 中指定两个冲突的 AspectJ 版本也没有帮助。我建议仅使用最新版本的 AspectJ 1.9.20.1。

© www.soinside.com 2019 - 2024. All rights reserved.