首页 > 代码库 > spring aop

spring aop

一、schema方式


1. 增加代码

package com.tcf.aop;

import java.util.Arrays;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

public class BeforeLogging {
    private Logger log = Logger.getLogger(BeforeLogging.class);
    public void  before(JoinPoint jp){
        String str = String.format("执行了%s方法,参数为:%s",
                jp.getSignature().getName(),Arrays.toString(jp.getArgs()));
        log.info(str);
    }
    public void afterReturning(JoinPoint jp,Object val){
        String str = String.format("执行了%s方法,参数为:%s 返回值:%s",
                jp.getSignature().getName(),Arrays.toString(jp.getArgs()),
                val);
        log.info(str);
    }
    public void throwing(JoinPoint jp,Exception e){
        String str = String.format("执行了%s方法,参数为:%s 异常为:%s",
                jp.getSignature().getName(),Arrays.toString(jp.getArgs()),
                e.getMessage());
        log.info(str);
    }
    
    public void around(ProceedingJoinPoint pjp) throws Throwable{
        String str1 = String.format("环绕前:执行了%s方法,参数为:%s",
                pjp.getSignature().getName(),Arrays.toString(pjp.getArgs()));
        log.info(str1);
        //执行代理的方法
        Object val = pjp.proceed();
        //
        String str2 = String.format("环绕后:执行了%s方法,参数为:%s,返回值 :%s",
                pjp.getSignature().getName(),Arrays.toString(pjp.getArgs()),
                val);
        log.info(str2);
    }
    public void after(JoinPoint jp){
        String str = String.format("最终增强:执行了%s方法,参数为:%s",
                jp.getSignature().getName(),Arrays.toString(jp.getArgs()));
        log.info(str);
    }
}

2.applicationContext.xml

<bean id="before" class="com.tcf.aop.BeforeLogging" />
    <aop:config>
        <aop:pointcut expression="execution(public boolean addUser())" id="user"/>
        <aop:aspect ref="before" >
            <aop:before method="before" pointcut-ref="user"/>
            <aop:after-returning method="afterReturning" pointcut-ref="user" returning="val"/>
            <aop:after-throwing method="throwing" pointcut-ref="user" throwing="e"/>
            <aop:around method="around" pointcut-ref="user" />
            <aop:after method="after" pointcut-ref="user" />
        </aop:aspect>
    </aop:config>


二、注解方式

1.增强代码

package com.tcf.aop;

import java.util.Arrays;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class BeforeLogging2 {
    private Logger log = Logger.getLogger(BeforeLogging2.class);
    
    /**
     * 当前项目的jdk要使用1.6
     */
    @Pointcut("execution(public boolean addUser())")
    private void log(){
        
    }
    
    @Before("log()")
    /*@Before("execution(public boolean addUser())")*/
    public void  before(JoinPoint jp){
        String str = String.format("执行了%s方法,参数为:%s",
                jp.getSignature().getName(),Arrays.toString(jp.getArgs()));
        log.info(str);
    }
    
    @AfterReturning(pointcut="log()",returning="val")
    /*@AfterReturning(pointcut="execution(public boolean addUser())",returning="val")*/
    public void afterReturning(JoinPoint jp,Object val){
        String str = String.format("执行了%s方法,参数为:%s 返回值:%s",
                jp.getSignature().getName(),Arrays.toString(jp.getArgs()),
                val);
        log.info(str);
    }
    @AfterThrowing(pointcut="log()",throwing="e")
    /*@AfterThrowing(pointcut="execution(public boolean addUser())",throwing="e")*/
    public void throwing(JoinPoint jp,Exception e){
        String str = String.format("执行了%s方法,参数为:%s 异常为:%s",
                jp.getSignature().getName(),Arrays.toString(jp.getArgs()),
                e.getMessage());
        log.info(str);
    }
    @Around("log()")
    /*@Around("execution(public boolean addUser())")*/
    public void around(ProceedingJoinPoint pjp) throws Throwable{
        String str1 = String.format("环绕前:执行了%s方法,参数为:%s",
                pjp.getSignature().getName(),Arrays.toString(pjp.getArgs()));
        log.info(str1);
        //执行代理的方法
        Object val = pjp.proceed();
        //
        String str2 = String.format("环绕后:执行了%s方法,参数为:%s,返回值 :%s",
                pjp.getSignature().getName(),Arrays.toString(pjp.getArgs()),
                val);
        log.info(str2);
    }
    @After("log()")
    /*@After("execution(public boolean addUser())")*/
    public void after(JoinPoint jp){
        String str = String.format("最终增强:执行了%s方法,参数为:%s",
                jp.getSignature().getName(),Arrays.toString(jp.getArgs()));
        log.info(str);
    }
}

2.applicationContext.xml

<aop:aspectj-autoproxy />
<bean id="before" class="com.tcf.aop.BeforeLogging2" />

 

三、接口方式(advisor)


1.增强代码

package com.tcf.aop;

import java.lang.reflect.Method;
import java.util.Arrays;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

public class Logging3 implements MethodBeforeAdvice,AfterReturningAdvice,MethodInterceptor,ThrowsAdvice {
    private Logger log = Logger.getLogger(BeforeLogging2.class);
    
    public void before(Method arg0, Object[] arg1, Object arg2)
            throws Throwable {
        String str = String.format("执行了%s类的%s方法,参数为:%s",
                arg2.getClass().getName(),arg0.getName(),
                Arrays.toString(arg1));
        log.info(str);
    }

    public void afterReturning(Object arg0, Method arg1, Object[] arg2,
            Object arg3) throws Throwable {
        // TODO Auto-generated method stub
        String str = String.format("执行了%s类的%s方法,参数为:%s 返回值 :%s",
                arg3.getClass().getName(),arg1.getName(),
                Arrays.toString(arg2),arg0);
        log.info(str);
    }

    public Object invoke(MethodInvocation arg0) throws Throwable {
        // TODO Auto-generated method stub
        String str1 = String.format("环绕前:执行了%s方法,参数为:%s",
                arg0.getMethod().getName(),Arrays.toString(arg0.getArguments()));
        log.info(str1);
        //执行代理的方法
        Object val = arg0.proceed();
        //
        String str2 = String.format("环绕后:执行了%s方法,参数为:%s,返回值 :%s",
                arg0.getMethod().getName(),Arrays.toString(arg0.getArguments()),
                val);
        log.info(str2);
        return val;
    }
    
     /*public void afterThrowing(Method m, Object[] args, Object target,Throwable e) {
         String str = String.format("执行了%s方法,参数为:%s 异常为:%s",
                    m.getName(),Arrays.toString(args),
                    e.getMessage());
            log.info(str);
     }*/
     
     public void afterThrowing(Throwable e) {
         String str = String.format("异常为:%s",    e.getMessage());
            log.info(str);
     }
}


2.applicationContext.xml

<bean id="log3" class="com.tcf.aop.Logging3" />
    <aop:config>
        <aop:pointcut expression="execution(public boolean addUser())" id="user"/>
        <aop:advisor advice-ref="log3" pointcut-ref="user"/>
    </aop:config>


四、aop的beans信息

<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

</beans>

 

spring aop