6 Using aspects with Spring AOP
This chapter covers
- Aspect-oriented programming (AOP)
- Using aspects
- Using the aspect execution chain
Thus far, we have discussed the Spring context, and the only Spring capability we have used is DI, which is supported by the IoC principle. With DI, the framework manages objects you define, and you can request to use these objects where you need them. You learned that to request a bean’s reference, in most cases, you use the @Autowired annotation. When you request such an object from the Spring context, we say that Spring “injects” the object where you requested it. Now you’ll learn how to use another powerful technique supported by the IoC principle: aspects.
Aspects allow the framework to intercept method calls and add extra behavior to them. You use aspects when the same kind of logic is needed in many parts of the app, but that logic is not part of the method’s main job. For example, you might want to log when methods start and finish, check permissions before a method runs, measure how long a method takes, or manage transactions. Without aspects, you would need to repeat this logic in many methods. With aspects, you define the logic once and apply it where needed. This keeps the code cleaner, reduces duplication, and makes the app easier to maintain.