ASPECT Any AOP language has some crosscutting expressions that encapsulate the concern in one place. The difference between AOP languages lies in the power, safety, and usability of theconstructs provided. E.g., interceptors that specify the methods to intercept express a limited formof crosscutting, without much support for type-safety or debugging. AspectJ has a number of suchexpressions and encapsulates them in a special class, an aspect. For example, an aspect can alterthe behaviour of the base code (the non-aspect part of a program) by applying advice (additional behaviour) at various join points (points in a program) specified in a quantification or query calleda pointcut (that detects whether a given join point matches). An aspect can also make binary- compatible structural changes to other classes, like adding members or parents. Many AOP languages support method executions and field references as join points. In them the developer can write a pointcut to match, for example, all field-set operations on specificfields, and code to run when the field is actually set. Some also support things like defining a method in an aspect on another class. AOP languages can be compared based on the join pointsthey expose, the language they use to specify the join points, the operations permitted at the joinpoints, and the structural enhancements that can be expressed. When thinking of an object and its relationship to other objects we often think in terms ofinheritance. We define some abstract class; let us use a Dog class as an example. As we identifysimilar classes but with unique behaviours of their own, we often use inheritance to extend the functionality. For instance, if we identified a Poodle we could say a Poodle Is A Dog, so Poodleinherits Dog. So far so good, but what happens when we define another unique behaviour later onthat we label as an Obedient Dog? Surely not all Dogs are obedient, so the Dog class cannot contain the obedience behaviour. Furthermore, if we were to create an Obedient Dog class thatinherited from Dog, then where would a Poodle fit in that hierarchy? A Poodle is A Dog, but aPoodle may or may not be obedient; does Poodle, then, inherit from Dog, or does Poodle inheritfrom Obedient Dog? Instead, we can look at obedience as an aspect that we apply to any type of Dog that is obedient, as opposed to inappropriately forcing that behaviour in the Dog hierarchy.In software terms, aspect-oriented programming allows us the ability to apply aspects that alter behavior to classes or objects independent of any inheritance hierarchy. We can then applythese aspects either during runtime or compile time.
ADVICE Advice is a way of expressing a cross cutting action that needs to occur. Now that theaspect has defined the points it should log, it uses advice to accomplish the actual logging. Adviceis code that executes before, after, or around a join point. You define advice relative to a pointcut,saying something like "run this code after every method call I want to log." Hence the advice is the action taken by an aspect at a particular join point. Different types of advice include “around", "before" and "after" advice. Types of advice: Before advice: Advice that executes before a join point, but which does not have theability to prevent execution flow proceeding to the join point (unless it throws anexception). After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception. After throwing advice: Advice to be executed if a method exits by throwing an exception. After (finally) advice: Advice to be executed regardless of the means by which a join pointexits (normal or exceptional return). Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behaviour before andafter the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.Around advice is the most general kind of advice. JOINPOINT Join point is a point during the execution of a program, such as the execution of a methodor the handling of an exception. In Spring AOP, a join point always represents a methodexecution. Join point information is available in advice bodies by declaring a parameter of type : aspectJ. lang. JoinPoint. Joinpoint is the well defined points in code that can be identified. Think of a joinpoint as adefined point in program flow. A good example of a joinpoint is the following: when codeinvokes a method, that point at which that invocation occurs is considered the join point. The pointcut allows us to specify or define the joinpoints that we wish to intercept in our programflow. A Pointcut also contains an advice that is to occur when the joinpoint is reached. So if we define a Pointcut on a particular method being invoked, when the invocation occurs or the joinpoint is invoked, it is intercepted by the AOP framework and the pointcut's advice is executed. An advice can be several things, but you should most commonly think of it as another method to invoke. So when we invoke a method with a pointcut, our advice to execute would be another method to invoke. This advice or method to invoke could be on the object whose method was intercepted.
Join point models The advice-related component of an aspect-oriented language defines a join point model (JPM). A JPM defines three things: When the advice can run: These are called join points because they are points in a runningprogram where additional behavior can be usefully joined. A join point needs to beaddressable and understandable by an ordinary programmer to be useful. (It should also bestable across inconsequential program changes in order for an aspect to be stable acrosssuch changes.)A way to specify (or quantify) join points, called point cuts. Pointcuts determine whether a given join point matches. Most useful pointcut languages use a syntax like the baselanguage (e.g., Java signatures are used for AspectJ) and allow reuse through naming andcombination. A means of specifying code to run at a join point: In AspectJ, this is called advice, and canrun before, after, and around join points.
POINT- CUT Point- cut is a way of specifying a Joinpoint by some means of configuration or code. Pointcut is a predicate that matches join points. Advice is associated with a pointcut expression andruns at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP: Spring uses the AspectJ pointcut language by default. The pointcut allows us to specify or define the joinpoints that we wish to intercept in our program flow. A Pointcut also contains an advice that is to occur when the joinpoint is reached. So if we define a Pointcut on a particular method being invoked, when the invocation occurs orthe joinpoint is invoked, it is intercepted by the AOP framework and the pointcut's advice isexecuted. An advice can be several things, but you should most commonly think of it as anothermethod to invoke. So when we invoke a method with a pointcut, our advice to execute would be another method to invoke. This advice or method to invoke could be on the object whose methodwas intercepted.
CUT DESIGNATORS execution - for matching method execution join points, this is the primary pointcutdesignator you will use when working with Spring AOP. within - limits matching to join points within certain types (simply the execution of amethod declared within a matching type when using Spring AOP) this - limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type. target - limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type. args - limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types target - limits matching to join points (the execution of methods when using SpringAOP) where the class of the executing object has an annotation of the given type. args - limits matching to join points (the execution of methods when using Spring AOP)where the runtime type of the actual arguments passed have annotations of the giventype. annotation - limits matching to join points where the subject of the join point (methodbeing executed in Spring AOP) has the given annotation.
OVERVIEW OF AOP
When Object-Oriented (OO) programming entered the mainstream of software development, it had a dramatic effect on how software was developed. Developers could visualizesystems as groups of entities and the interaction between those entities, which allowed them totackle larger, more complicated systems and develop them in less time than ever before. The onlyproblem with OO programming is that it is essentially static, and a change in requirements canhave a profound impact on development timelines. Aspect-Oriented Programming (AOP) complements OO programming by allowing the developer to dynamically modify the static OO model to create a system that can grow to meetnew requirements. Just as objects in the real world can change their states during their lifecycles,an application can adopt new characteristics as it develops.Consider an example: many of you have developed simple web applications that use servlets as the entry point, where a servlet accepts the values of a HTML form, binds them to an object, passes them into the application to be processed, and then returns a response to the user.The first cut of the servlet may be very simple, with only the minimum amount of code requiredto fulfill the use case being modeled. The code, however, often inflates to three to four times itsoriginal size by the time secondary requirements such as exception handling, security, andlogging have been implemented. I use the term "secondary requirements" because a servlet should not need to know about the logging or security mechanisms being used; its primary function is toaccept input and process it.AOP allows us to dynamically modify our static model to include the code required tofulfill the secondary requirements without having to modify the original static model (in fact, wedon't even need to have the original code). Better still, we can often keep this additional code in asingle location rather than having to scatter it across the existing model, as we would have to ifwe were using OO on its own. Programs are decomposed into suitable cross-cutting building blocks, i.e. a building blockaffects many parts of the combined program. Building blocks which contain redundantinformation are over specified and need to be reduced to a description which removes theoverspecification. The reduced description is expressed in an aspect description language. Thisleads to a solution of a more general problem while at the same time removing the redundancyfrom the program. The reduced building blocks need to be compiled together into the original or an improved form of the original program. An important issue is how the reduced descriptions collaborate. They need to refer to a common vocabulary (join points) so that the compiler can regenerate the original program.To understand a program, we need to understand the aspects underlying the program. Toavoid manual aspect extrication and to ease evolution, it is better to express the aspects directly. Evolution is simplified, since changes to aspects are localized to an aspect description rather thanspread out through a program. Aspects should have the following properties: robust (change toone aspect should have a limited impact on other aspects), systemic (they affect the targetprogram at many different places), cross-cutting each other (in the target program informationabout one aspect is mixed with information about other aspects), loosely coupled (an aspect should not know the details of other aspects), contain join points (which are used to combine theaspects).
Join point models
The advice-related component of an aspect-oriented language defines a join point model (JPM). A JPM defines three things:
When the advice can run. These are called join points because they are points in a running program where additional behavior can be usefully joined. A join point needs to be addressable and understandable by an ordinary programmer to be useful. It should also be stable across inconsequential program changes in order for an aspect to be stable across such changes. Many AOP implementations support method executions and field references as join points.
A way to specify (or quantify) join points, called pointcuts. Pointcuts determine whether a given join point matches. Most useful pointcut languages use a syntax like the base language (for example, AspectJ uses Java signatures) and allow reuse through naming and combination.
A means of specifying code to run at a join point. AspectJ calls this advice, and can run it before, after, and around join points. Some implementations also support things like defining a method in an aspect on another class.
ARCHITECTURE OF ASPECT ORIENTED PROGRAMMING
MOTIVATION AND BASIC CONCEPTS
Some code is scattered or tangled, making it harder to understand and maintain. It isscattered when one concern (like logging) is spread over a number of modules (e.g., classes andmethods). That means to change logging can require modifying all affected modules. Modules end up tangled with multiple concerns (e.g., account processing, logging, and security). Thatmeans changing one module entails understanding all the tangled concerns. For example, consider a banking application with a conceptually very simple method fortransferring an amount from one account to another:However, in a real-world banking application, this transfer method seems far from adequate. It requires security checks to verify that the current user has the authorization to perform this operation. The operation should be in a database transaction in order to preventaccidental data loss. For diagnostics, the operation should be logged to the system log. And so on.The code has lost its elegance and simplicity because the various new concerns have become tangled with the basic functionality (sometimes called the business logic concern). Transactions, security, and logging all exemplify cross-cutting concerns. (This particular examplemay not be the best as this represents a failure to properly factor classes: a transfer should be itsown object.) Also consider what happens if we suddenly need to change (for example) the securityconsiderations for the application. In the program's current version, security-related operationsappear scattered across numerous methods, and such a change would require a major effort. Therefore, we find that the cross-cutting concerns do not get properly encapsulated in theirown modules. This increases the system complexity and makes evolution considerably more difficult. AOP attempts to solve this problem by allowing the programmer to express cross-cutting concerns in stand-alone modules called aspects. Aspects can contain advice (code joined to specified points in the program) and inter-type declarations (structural members added to other classes). For example, a security module can include advice that performs a security check beforeaccessing a bank account. The pointcut defines the times (join points) that a bank account can beaccessed, and the code in the advice body defines how the security check is implemented. That way, both the check and the places can be maintained in one place. Further, a good pointcut can anticipate later program changes, so if another developer creates a new method to access the bankaccount, the advice will apply to the new method when it executes. AOP concepts Let us begin by defining some central AOP concepts. Unfortunately, AOP terminology is not particularly intuitive; however, it would be even more confusing if spring used its own terminology.
Aspect: A modularization of a concern that cuts across multiple objects. Transaction management is a good example of a crosscutting concern in J2EE applications. In SpringAOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with theAspect annotation AspectJ style).
Join point: A point during the execution of a program, such as the execution of a methodor the handling of an exception. In Spring AOP, a join point always represents a methodexecution. Join point information is available in advice bodiesby declaring a parameter oftype “aspectj.lang.JoinPoint”.
Advice:Action taken by an aspect at a particular join point. Different types of adviceinclude "around," "before" and "after" advice. Advice types are discussed below. ManyAOP frameworks, including Spring, model an advice as an interceptor, maintaining achain of interceptors "around" the join point.
Pointcut: A predicate that matches join points. Advice is associated with a pointcutexpression and runs at any join point matched by the pointcut (for example, the executionof a method with a certain name). The concept of join points as matched by pointcutexpressions is central to AOP: Spring uses the AspectJ pointcut language by default.
Introduction:(Also known as an inter-type declaration). Declaring additional methods orfields on behalf of a type. Spring AOP allows you to introduce new interfaces (and acorresponding implementation) to any proxied object. For example, you could use anintroduction to make a bean implement anIsModified interface, to simplify caching.
Target object: Object being advised by one or more aspects. Also referred to as theadvised object. Since Spring AOP is implemented using runtime proxies, this object willalways be a proxied object.
AOP proxy: An object created by the AOP framework in order to implement the aspectcontracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy. Proxy creation is transparent to users ofthe schema-based and AspectJ styles of aspect declaration introduced in Spring 2.0.
Weaving: Linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), loadtime, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weavingat runtime.
Aspect Weaver AOP is a new technology for separating crosscutting concerns into single units calledaspects. An aspect is a modular unit of crosscutting implementation. It encapsulates behaviours that affect multiple classes into reusable modules. With AOP, we start by implementing our projectusing our OO language (for example, Java), and then we deal separately with crosscuttingconcerns in our code by implementing aspects. Finally, both the code and aspects are combinedinto a final executable form using an aspect weaver. As a result, a single aspect can contribute tothe implementation of a number of methods, modules, or objects, increasing both reusability andmaintainability of the code. Figure explains the weaving process. It should note that the original code doesn't need to know about any functionality the aspect has added; it needs only to berecompiled without the aspect to regain the original functionality.