spring 基于AOP模拟日志打印

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Michaeles/article/details/85419058

一、控制方法执行打印日志、执行后打印日志、让指定方法打印日志

1.指定方法打印日志

(1)在invoke()方法中加一个对method名字的判断,其中method的名字可以写在xml文件中。

二、代码实现

1.ILogger代码

public interface ILogger {
     void start(Method method);
     void end(Method method);
 }
public class DLogger implements ILogger{
    @Override
    public void start(Method method) {
        System.out.println(new Date()+ method.getName() + " say hello start...");
    }
    @Override
    public void end(Method method) {
        System.out.println(new Date()+ method.getName() + " say hello end");
    }
}

2.动态代理类

public class DynaProxyHello1 implements InvocationHandler{
    //调用对象
    private Object proxy;
    //目标对象
    private Object target;
    
    public Object bind(Object target,Object proxy){
        this.target=target;
        this.proxy=proxy;
        return Proxy.newProxyInstance(this.target.getClass().getClassLoader(), this.target.getClass().getInterfaces(), this);
    }
    
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
        Object result = null;
        //反射得到操作者的实例
        Class clazz = this.proxy.getClass();
        //反射得到操作者的Start方法
        Method start = clazz.getDeclaredMethod("start", new Class[]{Method.class});
        //反射执行start方法
        start.invoke(this.proxy, new Object[]{this.proxy.getClass()});
        //执行要处理对象的原本方法
        result=method.invoke(this.target, args);
        //反射得到操作者的end方法
        Method end = clazz.getDeclaredMethod("end", new Class[]{Method.class});
        //反射执行end方法
        end.invoke(this.proxy, new Object[]{method});
        return result;
    }
    
}

3.测试代码

public interface IHello {
    /**
     * 业务方法
     * @param str
     */
    void sayHello(String str);
}
public class Hello implements IHello{
    @Override
    public void sayHello(String str) {
        System.out.println("hello "+str);
    }
    
}
public class DynaTest1 {
    public static void main(String[] args) {
        //如果我们需要日志功能,则使用代理类
        IHello hello = (IHello) new DynaProxyHello1().bind(new Hello(),new DLogger());
        //IHello hello = new Hello();//如果我们不需要日志功能则使用目标类
        hello.sayHello("明天");
    }
}

猜你喜欢

转载自blog.csdn.net/Michaeles/article/details/85419058