hguser
hguser

Reputation: 36028

how to pass context arguments to advice in spring aop

I am learning spring aop now,and I have no idea to pass context arguments to the advice.

Note I mean the context arguments,not the normal arguments.

It is simple to pass the normal arguments,for example:

a join point:
public void read(String something){

}

@Aspect
public class SessionAspect {
    @Pointcut("execution(* *.*(String)) &&args(something)")
    public void sess() {
    }

    @Before("sess()")
    public void checkSessionExist(String something) {
        //Here
    }
}

Then the something argument will be passed to the the advice checkSessionExist.

But how about I want to get the context arguments like HttpSession or something else?

a join point:

public void listUser(){
    dao.list(User.class,.....);
}

@Aspect
public class SessionAspect {
    @Pointcut("execution(* *.*(String))")
    public void sess() {
    }

    @Before("sess()")
    public void checkSessionExist(String something) {
        //Here
    }
}

In this example,the listUser join point is only allowed for logined user.

So I want to check if there is a identify in the current HttpSession,so I need to get an instance of HttpSession at the advice checkSessionExist.

But how to get it?

The simplest way is to add the HttpSession argumets to all the joit points like this:

public void listUser(HttpSession session){
    dao.list(User.class,.....);
}

However this have gone against the AOP it self. In my opinion,the join point even does not need to know the exist of the Aspect,isn't it?

How to fix it ?

Upvotes: 3

Views: 1695

Answers (1)

Vikram
Vikram

Reputation: 4190

Instead of passing HttpSession via @Pointcuts, you could fetch HttpSession reference in the @Aspect itself

RequestContextHolder.currentRequestAttributes()
.getAttribute("user", RequestAttributes.SCOPE_SESSION)

@Aspect
public class SessionAspect {

    // fetch the current HttpSession attributes and use as required 
    private ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();


    @Pointcut("execution(* *.*(String))")
    public void sess() {
    }

    @Before("sess()")
    public void checkSessionExist(String something) {
        //Here
    }
}

Upvotes: 1

Related Questions