java - 如何在java中的每个catch block 之前注入(inject)日志语句

标签 java jboss code-injection aop

我最初使用 JBoss 进行面向方面编程,并实现了代码注入(inject) - 调用方法之前和之后以及方法抛出异常之后。 现在我想知道我们如何在方法中注入(inject)代码?我想在每个 catch block 执行之前注入(inject)一个 Logging 语句,我们如何使用 java 来做到这一点?

最佳答案

我对 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

关于java - 如何在java中的每个catch block 之前注入(inject)日志语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30825537/

相关文章:

rest - OSGi JAX-RS 和 bnd 声明式服务

java - Struts2 自定义异常映射拦截器

java - 尽管跟踪模式 cookie,JBoss 7 仍将 JSESSIONID 附加到 URL

html - 为什么这 5(6?)个字符被视为 "unsafe"HTML 字符?

java - JBOSS如何识别EAR文件

java - JBWEB003006 : Handshake failed: java. io.IOException : JBWEB002042: SSL handshake failed, SSL session 中的密码套件是 SSL_NULL_WITH_NULL_NULL

php - JavaScript注入(inject)

java - 修剪有向图的叶子组件

java - 在catch block 中抛出异常没有用吗?

java - 变量命名接口(interface)