本文介绍了如何在Java中的每个catch块之前注入日志记录语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最初从使用JBoss进行面向方面的编程开始,并为-在调用该方法之前和之后以及该方法引发异常之后实现了它们的代码注入.现在我想知道我们如何在该方法中注入代码?我想在每个catch块执行之前注入Logging语句,我们如何使用Java做到这一点?

I initially started with Aspect Oriented Programming using JBoss , and have implemented their code injection for - Before and After the method gets called and After the Method Throws an Exception.Now i want to know how do we inject code within the method ? I want to inject a Logging statement before every catch block gets executed , How do we do that using java ?

推荐答案

我对JBoss AOP知之甚少,但是在任何情况下都可以使用AspectJ,因为它具有handler()切入点.

I do not know much about JBoss AOP, but in any case you can use AspectJ because it features a handler() pointcut.

驱动程序应用程序:

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中的每个catch块之前注入日志记录语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 14:26