简体   繁体   中英

Spring AOP: passing variables between advice and annotated methods

I'm writing some methods to deal with database operations. Each method first gets a connection, do the operations, and close the connection at end.

I wonder if Spring AOP can help handling the connection acquiring and closing. Specifically I want something like:

@Aspect
@Component
public class ConnAspect {
    @Around("@annotation(connHandle)")
    public void handleConnection(ProceedingJoinPoint pjp, ConnHandle connHandle) throws Throwable {
        Connection conn = datasource.getConnection();
        pjp.proceed(); // can pjp get variable conn?
        conn.close();
    }
}

@Component
public class DbOperation {
    @ConnHandle
    public void operation1(...) {
        ... // do some operation with conn
    }
    ...
}

Is it possible to do so? Or should I turn to other solutions? Thanks for any hints and answers.

No, this is not possible, and the suggestions in the comments are not going to help you. You cannot magically inject a non-existent method parameter or local variable into a method. Besides, what you are trying to do is anti AOP: not to encapsulate your cross-cutting concern in an aspect, but somehow bleed aspect context into your application, which ideally should be unaware of the aspect and work without it. You should rather describe what you want to achieve instead of being fixated on a specific (bad) design you have dreamed up to implement your idea.

Besides, there are simpler, reflective ways for a method to fetch its own annotations than to abuse AOP for that purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM