Aspects

An aspect is a modularization of such a concern. Instead of scattering code across many classes, we put the logic of handling the concern into an aspect. In Spring AOP, you can implement an aspect in a regular class and annotate it with the @Aspect annotation, which is an annotation from AspectJ (https://www.eclipse.org/aspectj).

Let's say we have methodA() in ClassA, methodB() in ClassB, and methodC() in ClassC, and we need to do security checking inside all of these methods. Before using AOP, we need to add code to handle security checks in all of these methods. And if we also need to execute a security check in other methods, we will need to add checkSecurity() to those methods too. After using AOP, we extract the security check logic into the SecurityChecker aspect, which is a regular Java class. And inside this class, the checkSecurity() method is annotated with the @Around annotation, which is an annotation from AspectJ. The value of the @Around annotation is an expression that is used to specify when the checkSecurity() method will be executed. In the example in Figure 3.7, the expression means whenever a method of any class inside the app.message package is executed:

Figure 3.7: AOP for security checking

With the @Around annotation, in runtime, the code execution will first reach the SecurityChecker.checkSecurity() method. Inside this method, you can decide whether the execution should proceed. If it should proceed, then you will invoke the target method and, once that method completes, the code execution will go back to the checkSecurity() method. At that point, normally you will return the code execution to the caller. On the other hand, if the execution should not proceed, you can throw an exception and the target method won't be executed.

As you can see from Figure 3.7, those methods requiring security checks no longer need the boilerplate code. All of the logic of the security checks has been centralized to the SecurityChecker aspect.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.252.204