使用spring的aop,可以在指定方法上增加切面,那么如何获取方法的参数(实参)呢?

示例如下:

com.shop.jn.service.UserService的login(ActionContext actionContext,User user) 方法上增加切面,并且在切面方法中获取该方法的参数(ActionContext actionContext,User user)。

beans.xml中部分代码如下:

<aop:config>


<aop:pointcut id="userServicePointcut"

expression="execution(* com.shop.jn.service.*.login(..)) and args(actionContext,user)" />

<aop:aspect id="myAspect" ref="loginTimesAop">

<aop:around pointcut-ref="userServicePointcut" method="around"

arg-names="actionContext,user" />

</aop:aspect>

</aop:config>


切面方法如下:

public Object around(ProceedingJoinPoint call, ActionContext actionContext,
            User user) throws Throwable {
        String aop_info = "aop[" + this.getClass().getSimpleName() + "]:";
        logger.info( aop_info+"This is around method.");
        if (timesFail >= Utils.MAX_LOGIN_FAIL_TIMES - 1) {
            if (!isLocked) {// first into this if clause
                task = null;
            }
            // ValueStack stack = actionContext.getValueStack();
            // stack.set("MESSAGE_IS_LOGIN", "You have failed " + timesFail
            // + " times.");
            if (timer == null) {
                timer = new Timer();
            }
            if (isLocked) {// over three times and is still locked,meanwhile use
                            // try to log in
                if (task != null) {
                    logger.info(aop_info+"cancel task.");
                    task.cancel();
                    task = null;
                }
            }
            logger.info(aop_info+"start task....");
            if (task == null) {
                task = new MyTask(this);
            }
            timer.schedule(task, Utils.MILLISECONDS_WAIT_WHEN_FAIL);
            isLocked = true;
            return Utils.LOGIN_RESULT_OVER_TIMES;// not success
        }
        Object obj = call.proceed();
        int resultCode = (Integer) obj;
        if (resultCode == Utils.LOGIN_RESULT_SUCCESS) {
            timesFail = 0;
        } else {
            timesFail++;
            logger.info(aop_info+"times of fail:" + timesFail+" times.");
        }
        return obj;
    }


注意:下面的配置是错误的:



<aop:config>
        <aop:pointcut id="userServicePointcut"
            expression="execution(* com.shop.jn.service.*.login(..)) and args(ActionContext,User)" />
        <aop:aspect id="myAspect" ref="loginTimesAop">
            <aop:around pointcut-ref="userServicePointcut" method="around"
                arg-names="actionContext,user" />
        </aop:aspect>
</aop:config>


说明:

(1)在pointcut中精确匹配到参数时,使用args,args中是参数列表,不包括参数类型;

(2)arg-names中指定的参数名称与args中的参数名称必须是一致的