简体   繁体   English

Spring AOP:在建议和注释方法之间传递变量

[英]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.我想知道 Spring AOP 是否可以帮助处理连接获取和关闭。 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.此外,您正在尝试做的是反 AOP:不要将您的横切关注点封装在一个方面,而是以某种方式将方面上下文引入您的应用程序,理想情况下应该不知道该方面并在没有它的情况下工作。 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.此外,与为此目的滥用 AOP 相比,方法有更简单、更反思的方法来获取自己的注解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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