Professional Documents
Culture Documents
Rani 2
Rani 2
Rani 2
Seminar Report On
Submitted by
RANI AUGUSTINE
KOCHI-682022
2007
ACKNOWLEDGEMENT
I thank GOD almighty for guiding me throughout the seminar. I would like to
thank all those who have contributed to the completion of the seminar and helped me with
Computer Science, for providing me with best facilities and atmosphere for the creative work
guidance and encouragement. I would like to thank my coordinator, Dr. Sumam Mary Idicula for
all help and support extend to me. I thank all staff members of my college and friends for
Above all I would like to thank my parents without whose blessings; I would not
ABSTRACT
Separation of concerns entails breaking down a program into distinct parts that overlap in
functionality as little as possible. All programming methodologies—including procedural
programming and object-oriented programming—support some separation and encapsulation of
concerns (or any area of interest or focus) into single entities. For example, procedures, packages,
classes, and methods all help programmers encapsulate concerns into single entities. But some
concerns defy these forms of encapsulation. Software engineers call these crosscutting concerns,
because they cut across many modules in a program.
AOP is a new technology for separating crosscutting concerns into single units called
aspects. An aspect is a modular unit of crosscutting implementation. It encapsulates behaviors that
affect multiple classes into reusable modules.
INDEX
1. INTRODUCTION………………………………………………………………….5
3. TERMINOLOGY…………………………………………………………………..7
3.2 ASPECT…………………………………………………………………..11
3.3 ADVICE…………………………………………………………………..13
3.4 JOINPOINT………………………………………………………………..14
3.5 POINT-CUT………………………………………………………………..16
4. OVERVIEW OF AOP………………………………………………………………18
6. ASPECTJ………………………………………………………………………….26
9. CONCLUSION……………………………………………………………………..39
10. REFERENCES……………………………………………………………………40
INTRODUCTION
OOP encourages software re-use by providing design and language constructs for
modularity, encapsulation, inheritance, and polymorphism. Although OOP has met great success
in modeling and implementing complex software systems, it has its problems. Practical
experience with large projects has shown that programmers may face some problems with
maintaining their code because it becomes increasingly difficult to cleanly separate concerns into
modules. An attempt to do a minor change in the program design may require several updates to a
large number of unrelated modules.
AOP is a new technology for separating crosscutting concerns into single units called
aspects. An aspect is a modular unit of crosscutting implementation. It encapsulates behaviors that
affect multiple classes into reusable modules. With AOP, we start by implementing our project
using our OO language (for example, Java), and then we deal separately with crosscutting
concerns in our code by implementing aspects. Finally, both the code and aspects are combined
into a final executable form using an aspect weaver. As a result, a single aspect can contribute to
the implementation of a number of methods, modules, or objects, increasing both reusability and
maintainability of the code.
GOAL OF AOP
In the early days of computer science, developers wrote programs by means of direct
machine-level coding. Unfortunately, programmers spent more time thinking about a particular
machine's instruction set than the problem at hand. Slowly, we migrated to higher-level languages
that allowed some abstraction of the underlying machine. Then came structured languages; we
could now decompose our problems in terms of the procedures necessary to perform our tasks.
However, as complexity grew, we needed better techniques. Object-oriented programming (OOP)
let us view a system as a set of collaborating objects. Classes allow us to hide implementation
details beneath interfaces. Polymorphism provided a common behavior and interface for related
concepts, and allowed more specialized components to change a particular behavior without
needing access to the implementation of base concepts.
TERMINOLOGY
Before we delve too deeply into AOP, let's introduce some standard
terminology to help us understand the concepts.
1. Cross-cutting concerns: Even though most classes in an OO model will perform a single,
specific function, they often share common, secondary requirements with other classes.
For example, we may want to add logging to classes within the data-access layer and also
to classes in the UI layer whenever a thread enters or exits a method. Even though the
primary functionality of each class is very different, the code needed to perform the
secondary functionality is often identical.
2. Advice: This is the additional code that you want to apply to your existing model. In our
example, this is the logging code that we want to apply whenever the thread enters or exits
a method.
3. Point-cut: This is the term given to the point of execution in the application at which
cross-cutting concern needs to be applied. In our example, a point-cut is reached when the
thread enters a method, and another point-cut is reached when the thread exits the method.
4. Aspect: The combination of the point-cut and the advice is termed an aspect. In the
example below, we add a logging aspect to our application by defining a point-cut and
giving the correct advice.
Aspects should have the following properties: robust (change to one aspect should have
a limited impact on other aspects), systemic (they affect the target program at many different
places), cross-cutting each other (in the target program information about 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 the aspects).
Separation of concerns entails breaking down a program into distinct parts that overlap in
functionality as little as possible. All programming methodologies—including procedural
programming and object-oriented programming—support some separation and encapsulation of
concerns (or any area of interest or focus) into single entities. For example, procedures, packages,
classes, and methods all help programmers encapsulate concerns into single entities. But some
concerns defy these forms of encapsulation. Software engineers call these crosscutting concerns,
because they cut across many modules in a program.
An example of crosscutting concerns is "logging," which is frequently used in distributed
applications to aid debugging by tracing method calls. Suppose we do logging at both the
beginning and the end of each function body. This will result in crosscutting all classes that have
at least one function. Other typical crosscutting concerns include context-sensitive error handling,
performance optimization, and design patterns.
Crosscutting concerns may exist in some programs, especially large ones. However, in
some situations, redesign of the system might transform a crosscutting into an object. AOP
assumes that crosscutting concerns may exist in programs and can't be re-factored out of the
design in all situations.
Business
Logic
Concern
Identifier Security
Requirements Logging
Fig.1
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 the
constructs provided. E.g., interceptors that specify the methods to intercept express a limited form
of crosscutting, without much support for type-safety or debugging. AspectJ has a number of such
expressions and encapsulates them in a special class, an aspect. For example, an aspect can alter
the behavior of the base code (the non-aspect part of a program) by applying advice (additional
behavior) at various join points (points in a program) specified in a quantification or query called
a 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 specific
fields, 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 points
they expose, the language they use to specify the join points, the operations permitted at the join
points, and the structural enhancements that can be expressed.
When thinking of an object and its relationship to other objects we often think in terms of
inheritance. We define some abstract class; let us use a Dog class as an example. As we identify
similar classes but with unique behaviors 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 Poodle
inherits Dog. So far so good, but what happens when we define another unique behavior later on
that we label as an Obedient Dog? Surely not all Dogs are obedient, so the Dog class cannot
contain the obedience behavior. Furthermore, if we were to create an Obedient Dog class that
inherited from Dog, then where would a Poodle fit in that hierarchy? A Poodle is A Dog, but a
Poodle may or may not be obedient; does Poodle, then, inherit from Dog, or does Poodle inherit
from 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 behavior 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 apply
these aspects either during runtime or compile time.
ADVICE
Advice is a way of expressing a cross cutting action that needs to occur. Now that the
aspect has defined the points it should log, it uses advice to accomplish the actual logging. Advice
is 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 adviceis
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 the
ability to prevent execution flow proceeding to the join point (unless it throws an
exception).
• After returning advice: Advice to be executed after a join point completes normally: for
example, if a method returns without throwing an exception.
• After (finally) advice: Advice to be executed regardless of the means by which a join point
exits (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 behavior before and
after 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.
JOINPOINT
Join point is a point during the execution of a program, such as the execution of a method
or the handling of an exception. In Spring AOP, a join point always represents a method
execution. Join point information is available in advice bodies by declaring a parameter of type
org.aspectj.lang.JoinPoint.
Joinpoint is the well defined points in code that can be identified. Think of a joinpoint as a
defined point in program flow. A good example of a joinpoint is the following: when code
invokes a method, that point at which that invocation occurs is considered the joinpoint. 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 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.
POINT- CUT
• execution - for matching method execution join points, this is the primary pointcut
designator you will use when working with Spring AOP
• within - limits matching to join points within certain types (simply the execution of a
method 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 Spring
AOP) 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 given
type(s)
• @within - limits matching to join points within types that have the given annotation (the
execution of methods declared in types with the given annotation when using Spring
AOP)
• @annotation - limits matching to join points where the subject of the join point (method
being executed in Spring AOP) has the given annotation
OVERVIEW OF AOP
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 required
to fulfill the use case being modeled. The code, however, often inflates to three to four times its
original size by the time secondary requirements such as exception handling, security, and
logging 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 to
accept input and process it.
AOP allows us to dynamically modify our static model to include the code required to
fulfill the secondary requirements without having to modify the original static model (in fact, we
don't even need to have the original code). Better still, we can often keep this additional code in a
single location rather than having to scatter it across the existing model, as we would have to if
we were using OO on its own.
Programs are decomposed into suitable cross-cutting building blocks, i.e. a building block
affects many parts of the combined program. Building blocks which contain redundant
information are overspecified and need to be reduced to a description which removes the
overspecification. The reduced description is expressed in an aspect description language. This
leads to a solution of a more general problem while at the same time removing the redundancy
from 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.
STEPS OF AOP
Fig 2
For example, consider a banking application with a conceptually very simple method for
transferring 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 prevent
accidental 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 example
may not be the best as this represents a failure to properly factor classes: a transfer should be its
own object.)
Also consider what happens if we suddenly need to change (for example) the security
considerations for the application. In the program's current version, security-related operations
appear 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 their
own 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 before
accessing a bank account. The pointcut defines the times (join points) that a bank account can be
accessed, 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 bank
account, the advice will apply to the new method when it executes.
AOP concepts
• Join point: A point during the execution of a program, such as the execution of a method
or the handling of an exception. In Spring AOP, a join point always represents a method
execution. Join point information is available in advice bodiesby declaring a parameter of
type org.aspectj.lang.JoinPoint.
• Advice: Action taken by an aspect at a particular join point. Different types of advice
include "around," "before" and "after" advice. Advice types are discussed below. Many
AOP frameworks, including Spring, model an advice as an interceptor, maintaining a
chain of interceptors "around" the join point.
• Pointcut: A predicate that matches join points. Advice is associated with a pointcut
expression and runs 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.
• Target object: Object being advised by one or more aspects. Also referred to as the
advised object. Since Spring AOP is implemented using runtime proxies, this object will
always be a proxied object.
• AOP proxy: An object created by the AOP framework in order to implement the aspect
contracts (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 of
the 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), load
time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving
at runtime.
Aspect Weaver
AOP is a new technology for separating crosscutting concerns into single units called
aspects. An aspect is a modular unit of crosscutting implementation. It encapsulates behaviors that
affect multiple classes into reusable modules. With AOP, we start by implementing our project
using our OO language (for example, Java), and then we deal separately with crosscutting
concerns in our code by implementing aspects. Finally, both the code and aspects are combined
into a final executable form using an aspect weaver. As a result, a single aspect can contribute to
the implementation of a number of methods, modules, or objects, increasing both reusability and
maintainability 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 be
recompiled without the aspect to regain the original functionality.
ASPECTJ
Aspect Oriented Programming and Java
}
public static void main (String[] args) {
sayHello ();
sayAnyThing ("ok");
}
}
Listing 1: TestClass.java
Now, we have our existing Java code in TestClass.java. Let's assume that we want to use aspects
to do the following modifications:
We would like to print a message before and after any call to the TestClass.sayHello() method.
We need to test that the argument of the TestClass.sayAnyThing() method is at least three
characters.
The following list is the AspectJ implementation.
1: public aspect MyAspect {
2: public pointcut sayMethodCall (): call (public void
TestClass.say*() );
3: public pointcut sayMethodCallArg (String str): call
(public void TestClass.sayAnyThing (String))
&& args(str);
4: before(): sayMethodCall() {
5: System.out.println("\n TestClass." +
thisJoinPointStaticPart.getSignature().getName() +
"start..." );
6: }
7: after(): sayMethodCall() {
8: System.out.println("\n TestClass." +
thisJoinPointStaticPart.getSignature().getName() +
" end...");
9: }
15: }
16: }
Listing 2: MyAspect.aj
Line 1 defines an aspect in the same way we define a Java class. Like any Java class, an aspect
may have member variables and methods. In addition, it may include pointcuts, advices, and
introductions.
In Lines 2 and 3, we specify where in the TestClass code our modification will take place. In
AspectJ terms, we define two pointcuts. To explain what a pointcut means, we first need to define
join points.
Join points represent well-defined points in a program's execution. Typical join points in AspectJ
include method/constructor calls, method/constructor execution, field get and set, exception
handler execution, and static and dynamic initialization. In our example, we have two join points:
the call to TestClass.sayHello and TestClass.sayAnyThing methods.
Pointcut is a language construct that picks out a set of join points based on defined criteria. The
criteria can be explicit function names, or function names specified by wildcards.
public pointcut sayMethodCall (): call (public void
TestClass.say*() );
In the preceding line, we define a pointcut, named sayMethodCall, that picks out any call to the
TestClass.sayHello method. Moreover, it picks out any public TestClass method with zero
arguments and a name that starts with "say" (for example, TestClass.sayBye).
Pointcuts are used in the definition of advice. An advice in AspectJ is used to define additional
code to be executed before, after, or around join points. In our example, Lines 4–6 and 7–9 define
two advices that will be executed before and after the first pointcut. Finally, Lines 10–15
implement an advice associated with the second pointcut and are used to set a precondition before
the execution of the TestClass.sayAnyThing method.
Whereas pointcuts and advice let you affect the dynamic execution of a program, introduction
allows aspects to modify the static structure of a program. By using introduction, aspects can add
new methods and variables to a class, declare that a class implements an interface, or convert
checked to unchecked exceptions. Introduction and a more practical application of AOP will be
the subject of a future article.
AspectJ Compiler
Initially, you have to download the most recent version of AspectJ, available for free at its
official site and install it. Compiling and running our example is very easy. Just write:
ajc MyAspect.aj TestClass.java
java TestClass
You should note that the source code at TestClass.java didn't change. To return to the original
functionality of your program, just use your Java compiler to re-compile it.
Now that you have better sense of what aspect code looks like, let's turn our attention
briefly to the business of writing aspects. In other words, let's answer the question, "How can I get
the above code to work?"
For aspects to affect regular class-based code, the aspects must be woven into the code
they modify. To do this using AspectJ, you must compile your class and aspect code with the ajc
compiler. ajc can operate either as a compiler or a precompiler, generating either valid .class or
.java files, which you can then compile and run in any standard Java environment (with the
addition of a small run-time JAR).
To compile with AspectJ, you will need to explicitly specify the source files (both aspect
and class) that you want to include in a given compilation -- ajc does not simply search your
classpath for relevant imports the way javac does. This makes sense because each class in a
standard Java application acts as a somewhat isolated component. A class needs only the presence
of classes that it directly references in order to operate correctly. Aspects represent aggregate
behaviors that span multiple classes. Therefore, an AOP program needs to be compiled as a unit
rather than one class at a time.
By specifying the files that are included in a given compilation, you can also plug and
unplug various aspects of your system at compile time. For instance, by including or excluding
the logging aspect described earlier from a compilation, the application builder can add or remove
method tracing from the Cactus framework.
An important limitation to the current version of AspectJ is that its compiler can only
weave aspects into code for which it has the source. In other words, you cannot use ajc to add
advice to precompiled classes. The AspectJ team regards this limitation as temporary, and the
AspectJ Web site promises that a future version (officially 2.0) will allow bytecode modification.
Tool support
Several development tools are included as part of AspectJ's release. This bodes well for
AspectJ's future, because it indicates a strong commitment on the part of the authors to making
AspectJ friendly to developers. Tool support is particularly important for an aspect-oriented
system because program modules can be affected by other modules of which they have no
knowledge.
One of the most important tools released with AspectJ is a graphical structure browser that
reveals at a glance how aspects interact with other system components. This structure browser is
available as a plug-in for popular IDEs as well as a stand-alone tool. Figure 1 shows a view of the
logging example discussed earlier.
A @Transactional annotation on a class specifies the default transaction semantics for the
execution of any public operation in the class.
Designers have considered alternative ways to achieve separation of code, such as C#'s
partial types, but such approaches lack a quantification mechanism that allows reaching several
join points of the code with one declarative statement.
Procedural programming
In AOP aspects are run at certain join points specified in the program.
Complements OOP
Class – code unit that encapsulates Aspect – code unit that encapsulates
Method signatures – define the entry Pointcut – define the set of entry points
points for the execution of method bodies. (triggers) in which advice is executed.
ADVANTAGES
The major advantages while using the AOP are follows:
• The code can be reusable and therefore reduce the redundancy of code.
These advantages of AOP helps the programmers for developing more powerful
soft wares.
DISADVANTAGES
Although AOP has several advantages it has some disadvantages.
• There may be a chance for reduce quality of software if aspects are not appropriately
managed.
CONCLUSION
REFERENCE
http://en.wikipedia.org/wiki/Aspect-oriented_programming
http://www.developer.com/design/article.php/3308941
http://java-source.net/open-source/aspect-oriented-frameworks
http://www.aopworld.com