天天看点

面向切片编程(AOP)应用的一些实际例子

The definition of AOP in wikipedia seems a little bit difficult for beginners to understand, so in this blog I use an example to introduce why we need it.

Suppose I have an order command class which performs its core business logic in method doBusiness:

面向切片编程(AOP)应用的一些实际例子
面向切片编程(AOP)应用的一些实际例子

It is not a good design, we can try to improve it via template method pattern.

Template method pattern

With this pattern, I create a new parent class BaseCommand, and put all non-functional code inside the execute method.

面向切片编程(AOP)应用的一些实际例子

Drawback of this solution: as the parent class has defined the template method execution, it is NOT possible for a child class to adapt it, for example, a child class cannot change the order sequence of authorization check and performance trace method. And suppose a child class does not want to implement authorization check at all – this could not be achieved with this solution. We have to use decorator pattern instead.

Decorator pattern

First I need to create an interface:

面向切片编程(AOP)应用的一些实际例子
面向切片编程(AOP)应用的一些实际例子

Drawback of decorator pattern: The decorator class and the business class have to implement the same interface, command, which is more business related. Is there possibility that the utility classes for non-functional implementation can just work without implementing the same interface which is implemented by business class?

AOP solution

I use a Java project implemented by Spring framework to demonstrate the idea.

Suppose I hope to add performance trace on this business method: save.

面向切片编程(AOP)应用的一些实际例子

(2) Now I have to declare an Aspect class which contains a pointcut. A pointcut tells Spring framework which methods could be applied with AOP strategy, and the class annotated with @Aspect contains methods which should be called by Spring framework to “decorate” the methods identified by annotation. Here below I have declared a pointcut “logJerry” via annotation @Pointcut:

面向切片编程(AOP)应用的一些实际例子

With this approach, I can add performance trace function to save method without modifying its source code.

Set breakpoint on these beforeExec and afterExec methods, launch the project with Tomcat under debug mode, paste the following url to your browser:

http://localhost:9498/springaop/aopRootJerry/aop2Jerry/i042416?string=sap

Through callstack you can understand how the AOP call is working in Spring.

面向切片编程(AOP)应用的一些实际例子
面向切片编程(AOP)应用的一些实际例子
面向切片编程(AOP)应用的一些实际例子
面向切片编程(AOP)应用的一些实际例子