如何在Java中每个catch块之前注入一个日志声明(How to inject a logging

2019-10-23 09:41发布

我最初使用JBoss开始面向方面的编程,并且已经实现了自己的代码注入了 - 之前和之后的方法被调用和之后,该方法会抛出异常。 现在,我想知道我们如何在方法中注入代码? 我想每一个catch块被执行之前,注入一个日志声明,我们怎样才能做到这一点使用Java?

Answer 1:

我不很了解的JBoss AOP,但在任何情况下,你可以使用AspectJ的,因为它的特点是handler()切入点。

驱动器应用:

package de.scrum_master.app;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeoutException;

import javax.naming.NamingException;

public class Application {
    public static void throwRandomException() throws TimeoutException, IOException, NamingException {
        switch (new Random().nextInt(5)) {
            case 0: throw new TimeoutException("too late, baby");
            case 1: throw new FileNotFoundException("file.txt");
            case 2: throw new IOException("no read permission");
            case 3: throw new NullPointerException("cannot call method on non-existent object");
            case 4: throw new NamingException("unknown name");
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            try { throwRandomException(); }
            catch (NullPointerException e) {}
            catch (FileNotFoundException e) {}
            catch (TimeoutException e) {}
            catch (IOException e) {}
            catch (NamingException e) {}
        }
    }
}

方面:

package de.scrum_master.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class CaughtExceptionLogger {
    @Before("handler(*) && args(e)")
    public void logCaughtException(JoinPoint thisJoinPoint, Exception e) {
        System.out.println(thisJoinPoint + " -> " + e.getMessage());
    }
}

控制台输出:

handler(catch(TimeoutException)) -> too late, baby
handler(catch(FileNotFoundException)) -> file.txt
handler(catch(NamingException)) -> unknown name
handler(catch(TimeoutException)) -> too late, baby
handler(catch(NamingException)) -> unknown name
handler(catch(NamingException)) -> unknown name
handler(catch(NullPointerException)) -> cannot call method on non-existent object
handler(catch(FileNotFoundException)) -> file.txt
handler(catch(FileNotFoundException)) -> file.txt
handler(catch(NullPointerException)) -> cannot call method on non-existent object


文章来源: How to inject a logging statement before every catch block in java