spring aop实现日志

      要用到这个接口 org.aspectj.lang.JoinPoint。这里有文档http://www.eclipse.org/aspectj/doc/released/runtime-api/

AspectJ使用org.aspectj.lang.JoinPoint接口表示目标类连接点对象,主要方法:

  java.lang.Object[] getArgs():获取连接点方法运行时的入参列表; 
  Signature getSignature() :获取连接点的方法签名对象; 
  java.lang.Object getTarget() :获取连接点所在的目标对象; 
  java.lang.Object getThis() :获取代理对象本身;

代码:

package service;

public interface Service {
    public void saySomething(int num,String str);
    public void doSomething(String name);
}
package service;

import org.springframework.stereotype.Component;

@Component("serviceImpl")
public class ServiceImpl implements Service {
    @Override
    public void saySomething(int num, String str) {
        
    }
    @Override
    public void doSomething(String name) {
        
    }
}

切面:

package advice;

import java.util.Calendar;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class Advice{
    @Before("init()")
    public void log(JoinPoint jp){
        System.out.println(jp.getKind());
        System.out.println("开始记录日志:");
        String className = jp.getThis().toString();
        String methodName = jp.getSignature().getName();
        System.out.println(Calendar.getInstance().getTime());
        System.out.println("调用" + className + "类的方法:" + methodName);
        
        Object[] obj = jp.getArgs();
        
        if(obj.length <= 0){
            System.out.println("没有参数");
        }else{
            for(int i = 0; i < obj.length ; i++){
                System.out.println("参数" + (i+1) + ":" + obj[i]);
            }
        }
        
    }
    
    @Pointcut("execution(* service.*.*(..))")
    public void init(){
        
    }

}

测试:

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext ac = new ClassPathXmlApplicationContext("service/bean.xml");
        Service ser =  (Service) ac.getBean("serviceImpl");
        ser.saySomething(123,"test");
        ser.doSomething("test");
    }

xml:

    <context:annotation-config></context:annotation-config>
    <context:component-scan base-package="service,advice"></context:component-scan>
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

 

posted @ 2016-05-05 15:41  长不高  阅读(200)  评论(0编辑  收藏  举报