理解 Spring AOP

发布于 2024-10-31 09:23:10 字数 1436 浏览 4 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

天冷不及心凉 2024-11-07 09:23:10

AOP 是一种修改代码库中现有类的方法,以根据单独定义的规则来修饰它们或更改它们的行为。此修改可以在将类放入 jar/war 之前完成,也可以在加载代码时动态进行。

这个想法是,你不是在源代码中找到你想要修改的所有代码点并手动修改它们,而是定义如何在代码库中找到感兴趣的点以及你想要做哪些修饰的规则。他们。这些规则称为方面(AOPA)。

典型的示例是您想要获取代码库中各种方法的一些计时信息。您可以找到所有感兴趣的方法,然后在顶部调用

long start = System.currentTimeMillis();

并在最后执行,

long end = System.currentTimeMillis();
System.out.println("Method time is: " + (end - start));

但这就是:

  1. 可能是一堆
  2. 临时工作,并且您不想弄乱您的代码库

您可以定义方面说明您想要修改哪些方法,以及您想要在这些方法的开头和结尾做一些事情。

当应用 AOP 时,无论是在 jar 创建时还是在类加载时,就好像您最初是这样编写类的。

AOP is a way to modify existing classes in a code base to embellish them or change their behavior based on rules defined separately. This modification can be done before the classes are put into a jar/war, or can happen dynamically while the code is being loaded.

The idea is, rather than finding all the points of code that you want to modify in the source code and hand modifying them, you define rules for how to find points of interest in the code base, and what embellishments you would like to do to them. These rules are called aspects (the A of AOP).

The prototypical example is you want to get some timing information on various methods in your code base. You could go find all the methods of interest and at the top put a call to

long start = System.currentTimeMillis();

and at the end do

long end = System.currentTimeMillis();
System.out.println("Method time is: " + (end - start));

but that is:

  1. probably a bunch of work
  2. temporary, and you don't want to muck up your code base

You can instead define aspects that say what methods you want to modify, and that you want to do stuff at the beginning and end of these methods.

When the AOP is applied, either at jar creation time, or class loading time, it's as if you wrote the classes that way originally.

巴黎盛开的樱花 2024-11-07 09:23:10

AOP 是一种模式用于模块化横切功能。因此,如果某个“事物”适用于代码中的重要部分,那么您可以使用 AOP 来解决该问题。这些“事物”称为方面。

下面的示例:

在整个企业应用程序中使用异常记录器。因此,您可以按照以下方式使用 AOP 进行设置。所以现在 my.service 包下的所有方法都将按以下方式记录。

  <bean id="exceptionLogger" class="my.good.ExceptionLogger" />  
        <aop:config>
                <aop:pointcut id="allServiceMethods" expression="execution(* my.service.*(..))" />
                <aop:aspect id="serviceLogger" ref="exceptionLogger">
                    <aop:after-throwing pointcut-ref="allServiceMethods"
                                        method="logIt"
                                        throwing="e"/>
                </aop:aspect>  
        </aop:config>

ExceptionLogger 类可能如下所示:-

public class ExceptionLogger {
    private static Logger logger = Logger.getLogger(ExceptionLogger.class);
    public void logIt(JoinPoint jp, Exception e) {
        StringBuilder msg = new StringBuilder();
        msg.append("<whatever makes sense>");
        logger.error(msg.toString());
    }
}

另请看一下这个相关问题:-

  1. Spring项目中AOP最常见的用途是什么

AOP is a pattern used to modularize cross cutting features. So if there is a certain "thing" that applies to a significant part in your code then you can use AOP to solve that problem. These "things" are called aspects.

An example below:

An exception logger is used across the enterprise app. So you could set it up using AOP the following way. So now all methods under my.service package will get logged the following way.

  <bean id="exceptionLogger" class="my.good.ExceptionLogger" />  
        <aop:config>
                <aop:pointcut id="allServiceMethods" expression="execution(* my.service.*(..))" />
                <aop:aspect id="serviceLogger" ref="exceptionLogger">
                    <aop:after-throwing pointcut-ref="allServiceMethods"
                                        method="logIt"
                                        throwing="e"/>
                </aop:aspect>  
        </aop:config>

And the ExceptionLogger class could be something like below:-

public class ExceptionLogger {
    private static Logger logger = Logger.getLogger(ExceptionLogger.class);
    public void logIt(JoinPoint jp, Exception e) {
        StringBuilder msg = new StringBuilder();
        msg.append("<whatever makes sense>");
        logger.error(msg.toString());
    }
}

Also take a look at this relevant question:-

  1. What is the most common use for AOP in spring project
南烟 2024-11-07 09:23:10

面向方面编程显然是一种新事物,它并不是面向对象编程的替代品。事实上,AOP 是组织程序结构的另一种方式。

为了更清楚,我将使用一些图表:

  1. 什么是方面?

    <前><代码>|--------------------|--------------------|-- ----------------|
    |方面=切入点+建议|
    |--------------------|--------------------|-------- ----------|
    | |纵横何处|代码是什么 |
    | |已应用 |被执行。 |
    |--------------------|--------------------|-------- ----------|

    方面 = 切入点 + 建议

  2. 建议方法类型

    在此处输入图像描述

  3. 方面示例

    @Around(“执行(* *(..))”)
    公共对象跟踪(ProceedingJoinPointproceedingJP)throwsThrowable{
        String methodInformation=procingJP.getStaticPart().getSignature().toString();
        logger.trace("正在输入"+methodInformation);
        尝试{
            returnproceedingJP.proceed();
        } catch(可抛出的前){
            logger.error("+methodInformation 中出现异常,例如);
            扔前;
        } 最后 {
             logger.trace("退出"+methodInformation);
        }
    }
    

Aspect Oriented Programming is sensibly new and it is not a replacement for Object Oriented Programming. In fact, AOP is another way of organizing your Program Structure.

To be more clear I will use some diagrams:

  1. What is Aspect?

    |---------------------|------------------|------------------|
    |      Aspect         =     Point cut    +  Advice          |
    |---------------------|------------------|------------------|
    |                     | Where the aspect | What code is     |
    |                     |  is applied      |  executed.       |
    |---------------------|------------------|------------------|
    

    Aspect = Point cut + Advice

  2. Type of Advice methods

    enter image description here

  3. Aspect Example

    @Around( "execution(* *(..))" )
    public Object trace(ProceedingJoinPointproceedingJP)throwsThrowable{
        String methodInformation= proceedingJP.getStaticPart().getSignature().toString();
        logger.trace("Entering "+methodInformation);
        try{
            returnproceedingJP.proceed();
        } catch(Throwable ex) {
            logger.error("Exception in "+methodInformation, ex);
            throw ex;
        } finally {
             logger.trace("Exiting "+methodInformation);
        }
    }
    
故事↓在人 2024-11-07 09:23:10

AOP 通过将横切关注点分离(模块)为方面来实现内聚开发。 简单来说,它只是一个拦截器,用于拦截一些流程,例如,当一个方法被执行时,Spring AOP可以劫持正在执行的方法,并在方法执行之前或之后添加额外的功能。

例如:日志记录、事务和安全性是一些方面。在日志记录中,我们可能有不同的方面,即时间计算日志记录、简单的进出消息日志记录等。

  • 建议定义了需要应用的内容。
  • 连接点是应用建议的地方。
  • 切入点是不同关节点的组合。
  • 方面正在切入点应用建议

注意:Spring 不支持标记为 Final 的方法的 AOP。

输入图像描述这里

来源


AOP 的工作方式类似于面向对象编程。在面向对象编程中,模块化的单位是对象,但在面向方面编程中,模块化的单位是方面Aspect 充当关注点的模块化,在 AOP 中称为横切关注点。 AOP框架在Spring中是可插拔的。 AOP 提供声明式企业服务并允许用户实现自定义方面。

源代码


Spring 使用 AOP 提供声明式编程。这是实现横切关注点的更好方法,而无需在整个核心业务类中使用管道代码。 AOP 使您能够思考系统中的问题或方面。典型的关注点是事务管理、日志记录等。AOP 使您能够捕获模块(例如拦截器)中的横切代码,这些模块可以以声明方式应用到它们所表达的关注点所在的任何地方。 Spring 包含一个基于代理的 AOP 框架。

来源

AOP enables cohesive development by separation(module) of Cross Cutting Concerns into Aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a method is execute, Spring AOP can hijack the executing method, and add extra functionality before or after the method execution.

For example: Logging, Transaction and security are some Aspects. In Logging we may have different aspect i.e. time calculation logging, simple in and out message logging and so on..

  • Advise defines what needs to be apply.
  • Joinpoint is where an Advice is apply.
  • Pointcut is a combination of different Jointpoints.
  • Aspect is applying an Advice at Pointcuts.

Note: Spring does not support AOP for methods marked as final.

enter image description here

Source


AOP works like Object Oriented Programming. In Object Oriented Programming, the unit of modularity is Object But in Aspect Oriented Programming the unit of modularity is Aspect. Aspect works as the modularization of concerns known as crosscutting concerns in AOP. AOP framework is pluggable in spring. AOP provides declarative enterprise service and allows users to implement custom aspects.

Source


Spring provides declarative programming with AOP. This is a better way to implement cross cutting concerns without the needs to use plumbing code all over the core business classes. AOP enables you to think about concerns or aspects in your system. Typical concerns are transaction management, logging etc. AOP enables you to capture the cross-cutting code in modules such as interceptors that can be applied declaratively wherever the concern they express applies. Spring includes a proxy-based AOP framework.

Source

浊酒尽余欢 2024-11-07 09:23:10

简而言之,AOP 是一种数学家的方式,它解释了应该如何整齐地组织代码,以避免特定功能分散在许多模块或对象中。从本质上讲,AOP 是一个好东西,无论它是否称为 AOP。

但你面对的是一个具体的AOP实现,需要弄清楚如何使用它。我认为最好的方法是寻找人们发布食谱以及如何将 Spring 与 Spring 一起使用的示例的博客。这样你就可以绕过数学家,阅读更贴近现实的工程师的著作。

有两种计算机科学家,一种是喜欢晦涩难懂的数学家,用晦涩难懂的术语来解释简单的事情,另一种是会一​​步步告诉你如何构建软件的工程师。在职程序员往往更具有工程师思维,因为抽象思考者发现很难处理长期积累经验的过程。这就是为什么你会觉得 AOP 很难理解。不是因为它难以理解,而是因为对“简单英语”不太熟悉的抽象数学思想家对它的解释非常糟糕。

我想知道如果 AOP 大师与功能点分析大师坐下来会发生什么。

In a nutshell, AOP is a mathematician's way of explaining how you should organize your code neatly to avoid having a particular functionality scattered in bits and pieces across lots of modules or object. At its heart, AOP is a good thing whether or not it is called AOP.

But you are faced with a specific AOP implementation and need to figure out how to use it. I think the best way to do this is to look for blogs where people post recipes and examples of how they are using it with Spring. This way you bypass the mathemeticians and get to read the writings of engineers who are more in touch with reality.

There are two kinds of computer scientists, mathematicians who delight in the obscure and use tortured terminology to explain simple things, and engineers who will tell you step by step how to build software. Working programmers tend to be more of the engineer mindset because abstract thinkers find it hard to handle the long slog of gaining experience. That's why you find AOP hard to understand. Not because it is hard to understand, but because it is explained so poorly by abstract mathematical thinkers who are not terribly familiar with "plain English".

I wonder what would happen if an AOP guru sat down with a Function Point Analysis guru.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文