java - Spring AOP: Aspect not working on called method -
this first time aop might noob question.
public class myaspect implements aspecti { public void method1() throws asyncapiexception { system.out.println("in method1. calling method 2"); method2(); } @retryoninvalidsessionid public void method2() throws asyncapiexception { system.out.println("in method2, throwing exception"); throw new asyncapiexception("method2", asyncexceptioncode.invalidsessionid); } public void login() { system.out.println("logging"); }
invalidsessionhandler looks this.
@aspect public class invalidsessionidhandler implements ordered { @around("@annotation(com.pkg.retryoninvalidsessionid)") public void reloginall(proceedingjoinpoint joinpoint) throws throwable { system.out.println("hijacked call: " + joinpoint.getsignature().getname() + " proceeding"); try { joinpoint.proceed(); } catch (throwable e) { if (e instanceof asyncapiexception) { asyncapiexception ae = (asyncapiexception) e; if (ae.getexceptioncode() == asyncexceptioncode.invalidsessionid) { system.out.println("invalid session id. relogin"); aspecti myaspect = (aspecti) joinpoint.gettarget(); myaspect.login(); system.out.println("login done. proceeding again now"); joinpoint.proceed(); } } } } @override public int getorder() { return 1; } }
spring configuration
<aop:aspectj-autoproxy /> <bean id="myaspect" class="com.pkg.myaspect" /> <bean id="invalidsessionidhandler" class="com.pkg.invalidsessionidhandler" />
my intent when call
myaspect.method1()
in turns callsmethod2
, ifmethod2
throwsinvalidsessionid
exception,method2
should retried. above code not seem anything. returns after exception thrown method2. if put@retryoninvalidsessionid
onmethod1
wholemethod1
retried.for learning kept
method2
public in actual wantprivate
. out of clue here, how retry private method.
any suggestions helpful.
thanks
this not possible current setup. spring's aop features, class invalidsessionidhandler
created bean , scanned annotations/method signatures/etc. relevant myaspect
class. find method2()
, therefore create proxy wrapping bean it's created. proxy have behavior advice.
spring inject (proxy) bean need it. example:
public class myclass { @autowired private myaspect aspect; public void callmethod2() { aspect.method2(); } }
in case, myclass
object has reference proxy. when calls aspect.method2()
, added behavior executed.
in code, however, you're expecting call method2()
within method1()
public void method1() throws asyncapiexception { system.out.println("in method1. calling method 2"); method2(); }
which within myaspect
class. technically, happening here method2()
getting called on this
this.method2()
. this
reference actual object, not proxy. therefore not execute additional behavior.
the aop spring documentation explains in more detail.
the workaround here refactor method2()
in class/object or call outside, ie. not method1()
.
Comments
Post a Comment