0% found this document useful (0 votes)
27 views

Advanced Java (Module 4)

The document discusses Aspect Oriented Programming (AOP) using Spring. It defines key AOP concepts like aspects, join points, advice, pointcuts, etc. It describes how AOP can increase modularity by separating cross-cutting concerns. The different types of advice in Spring AOP are before, after, after-returning, after-throwing and around advice. It also discusses pointcut designators and wildcards that can be used to define pointcuts in Spring.

Uploaded by

Sushma Sumant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Advanced Java (Module 4)

The document discusses Aspect Oriented Programming (AOP) using Spring. It defines key AOP concepts like aspects, join points, advice, pointcuts, etc. It describes how AOP can increase modularity by separating cross-cutting concerns. The different types of advice in Spring AOP are before, after, after-returning, after-throwing and around advice. It also discusses pointcut designators and wildcards that can be used to define pointcuts in Spring.

Uploaded by

Sushma Sumant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

C-4, Wagle Industrial Estate,

Near Mulund Check Naka,


Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

Advanced Java

Module 4

1|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

---------------------------------------------------------------------------------------------
Spring and AOP :
Aspect Oriented Programming with Spring, Types of advices, Defining Point Cut Designator,
Annotations.

Self learning topics: AspectJ

----------------------------------------------------------------------------------------------

What is Aspect Oriented Programming?

Aspect Oriented Programming (AOP) compliments OOPs in the sense that it also provides
modularity. But the key unit of modularity is aspect than class.
AOP breaks the program logic into distinct parts (called concerns). It is used to increase
modularity by cross-cutting concerns.
A cross-cutting concern is a concern that can affect the whole application and should be
centralized in one location in code as possible, such as transaction management,
authentication, logging, security etc.

Why should I use AOP anyway?

OOP promotes reusability and flexibility of code already. So, why then do you need AOP? AOP
is a programming paradigm that has all the benefits of OOP as well. Added to this, you can
promote loose coupling and enable your application to use pluggable aspects as and when
needed sans any change in your application's code. In using AOP, you can focus on the business
logic of your application while at the same time weave the aspects to the business logic. One
of the major benefits of using AOP is that you would just need to write your aspects once and
then you can reuse it wherever you need to in your application. So, AOP is a great way to
reduce the complexity of the source code of your application and make your code clean.

It provides the pluggable way to dynamically add the additional concern before, after or
around the actual logic. Suppose there are 10 methods in a class as given below:

class A{ public void m1(){...} public void m2(){...} public void m3(){...} public void
m4(){...} public void m5(){...} public void n1(){...} public void n2(){...} public void
p1(){...} public void p2(){...} public void p3(){...}

2|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

}
There are 5 methods that starts from m, 2 methods that starts from n and 3 methods that
starts from p.
Understanding Scenario I have to maintain log and send notification after calling methods
that starts from m.

Problem without AOP We can call methods (that maintains log and sends notification) from
the methods starting with m. In such scenario, we need to write the code in all the 5
methods.

But, if client says in future, I don't have to send notification, you need to change all the
methods. It leads to the maintenance problem.

Solution with AOP We don't have to call methods from the method. Now we can define the
additional concern like maintaining log, sending notification etc. in the method of a class. Its
entry is given in the xml file.

In future, if client says to remove the notifier functionality, we need to change only in the xml
file. So, maintenance is easy in AOP.

Where use AOP?

AOP is mostly used in following cases:


o to provide declarative enterprise services such as declarative transaction management.
o It allows users to implement custom aspects.

AOP concepts

Let us begin by defining some central AOP concepts and terminology. These terms are not
Spring-specific.

• Aspect : This is a module which has a set of APIs providing cross-cutting requirements.
For example, a logging module would be called AOP aspect for logging. An application
can have any number of aspects depending on the requirement.

3|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

• Join point : This represents a point in your application where you can plug-in the AOP
aspect. You can also say, it is the actual place in the application where an action will be
taken using Spring AOP framework.
• Advice : This is the actual action to be taken either before or after the method
execution. This is an actual piece of code that is invoked during the program execution
by Spring AOP framework.
• Pointcut : This is a set of one or more join points where an advice should be executed.
You can specify pointcuts using expressions or patterns.
• Introduction : An introduction allows you to add new methods or attributes to the
existing classes.
• Target object : The object being advised by one or more aspects. This object will
always be a proxied object, also referred to as the advised object.
• Weaving : Weaving is the process of linking aspects with other application types or
objects to create an advised object. This can be done at compile time, load time, or at
runtime.

An important term in AOP is advice. It is the action taken by an


aspect at a particular join-point. Joinpoint is a point of
execution of the program, such as the execution of a method
or the handling of an exception. In Spring AOP, a joinpoint
always represents a method execution. Pointcut is a predicate
or expression that matches join points. Advice is associated
with a pointcut expression and runs at any join point matched
by the pointcut. Spring uses the AspectJ pointcut expression
language by default.

Types of advice:

• Before : Run advice before the a method execution.


• After : Run advice after the method execution, regardless of its outcome.
• after-returning : Run advice after the a method execution only if method completes
successfully.

4|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

• after-throwing : Run advice after the a method execution only if method exits by
throwing an exception.
• Around : Run advice before and after the advised method is invoked.

Wildcards while defining expression

Wildcard Definition

.. This wildcard matches any number of arguments within method


definitions, and it matches any number of packages within the class
definitions.

+ This wildcard matches any subclasses of a given class.

* This wildcard matches any number of characters.

Defining Point Cut Designators


Spring AOP provides various matcher expressions in order to filter methods for applying the
advices to Spring beans. These are also called point cut designators. In this module we try to

5|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

cover the starting with the type signature expressions that could be used for package name–
or class name–based filtering; method signature expressions that could be used for filtering
methods based on their actual signatures; and bean name expressions that could be used for
filtering methods, which reside in a bean given with a name pattern. It’s also possible to
blend the expressions with grammatical operators: and, or, and not (or with &&, ||, and !).
So the sky is the limit in the designator world! The Type Signature Expressions For filtering
methods according to its types—like interfaces, class names, or package names—Spring AOP
provides the within keyword. The type signature pattern is as follows, and type name could
be replaced with package name or class name. within(<type name>) Here are some
examples for the type signature usages:

➤ within(com.test..*): This advice will match for all the methods in all classes of the
com.test package and all of its subpackages.
➤ within(com.test.spring.ch.MyService): This advice will match for all the methods in the
MyService class.
➤ within(MyServiceInterface+): This advice will match for all the methods of classes that
implement the MyServiceInterface.
➤ within(com.test.spring.ch.MyBaseService+): This advice will match for MyBaseService
class and for all of its subclasses.

The Method Signature Expressions


For filtering according to the method signatures, the execution keyword can be used. Its
pattern is stated as follows:
execution(<scope> <return-type> <fully-qualified-class-name>.*(parameters))
Here the methods that match with the given scope, return type, fully qualified class name,
and parameter will have the specified advice applied. The scope of the methods could either
be public, protected, or private. To bypass the parameter filtering, you can specify two dots
.., as we did for the advice definition in the earlier Try It Out activity, to say that the method
could have any number and type of parameters. The following are descriptions of the sample
method signatures:
➤ execution(* com.test.spring.ch.MyBean.*(..)): This advice will match for all the methods
of MyBean.

6|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

➤ execution(public * com.test.spring.ch.MyBean.*(..)): This advice will match for all the


public methods of MyBean.
➤ execution(public String com.test.spring.ch.MyBean.*(..)): This advice will match for all the
public methods of MyBean that return a String.
➤ execution(public * com.test.spring.ch.MyBean.*(long, ..)): This advice will match
for all the public methods of MyBean with the first parameter defined as long.

Other Alternative Point Cut Designators


This part lists the designators that are supported by the Spring AOP. AOP only supports a
subset of the designators that are available in the other AOP projects.
➤ bean(*Service): It’s possible to filter beans according to their names with the bean
keyword. The point cut expression given above will match for the beans that have the suffix
Service in their names.
➤ @annotation(com.test.spring.ch.MarkerMethodAnnotation): It’s possible to filter the
methods according to an annotation applied on. The point cut expression here states that the
methods that have the MarkerMethodAnnotation annotation will be advised.
➤ @within(com.test.spring.ch.MarkerAnnotation): While point cut expressions with the within
keyword match a package, class, or an interface, it’s also possible to restrict filtering of the
classes according to an annotation that the class would have. Here, the classes with the
MarkerAnnotation will be advised by the @within keyword.
➤ this(com.test.spring.ch.MarkerInterface): This point cut expression will filter the methods
of any proxy object that implements the MarkerInterface.

7|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

AOP Implementations

AOP implementations are provided by:


• AspectJ
• Spring AOP
• JBoss AOP

Spring AOP

Spring AOP can be used by 3 ways given below. But the widely used approach is Spring
AspectJ Annotation Style. The 3 ways to use spring AOP are given below:

• By Spring1.2 Old style (dtd based) (also supported in Spring3)


• By AspectJ annotation-style
• By Spring XML configuration-style(schema based)

8|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

Steps For Developing An XML Schema based Application

Aspects are implemented using the regular classes along with XML based
configuration.

1. Create a project with a name SpringExample and create a package com.test under the
src folder in the created project.

2. Add required Spring libraries using Add External JARs option.

3. Add Spring AOP specific libraries aspectjrt.jar, aspectjweaver.jar and aspectj.jar

4. Create Java classes Logging, Student and MainApp under the com.test package.

5. Create Beans configuration file Beans.xml under the src folder.

6. The final step is to create the content of all the Java files and Bean Configuration file
and run the application.

Here is the content of Logging.java file. This is actually a sample of aspect module which
defines the methods to be called at various points.

public class Logging {


//This is the method which I would like to execute before a selected method execution.
public void beforeAdvice(){
System.out.println("Going to setup student profile.");
}
//This is the method which I would like to execute after a selected method execution.
public void afterAdvice(){
System.out.println("Student profile has been setup.");
}

9|Page
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

//This is the method which I would like to execute when any method returns.
public void afterReturningAdvice(Object retVal) {
System.out.println("Returning:" + retVal.toString() );
}
//This is the method which I would like to execute if there is an exception raised.
public void AfterThrowingAdvice(IllegalArgumentException ex){
System.out.println("There has been an exception: " + ex.toString());
}
}
Following is the content of the Student.java file

public class Student {


private Integer age;
private String name;

public void setAge(Integer age) {


this.age = age;
}
public Integer getAge() {
System.out.println("Age : " + age );
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
System.out.println("Name : " + name );
return name;
}
public void printThrowException(){
System.out.println("Exception raised");
throw new IllegalArgumentException();
}
}

10 | P a g e
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

Following is the content of the MainApp.java file

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Student student = (Student) context.getBean("student"); student.getName();
student.getAge();
student.printThrowException();
}
}
Following is the configuration file Beans.xml

<?xml version = "1.0" encoding = "UTF-8"?>


<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:aop
= "http://www.springframework.org/schema/aop" xsi:schemaLocation =
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

<aop:config>
<aop:aspect id = "log" ref = "logging">
<aop:pointcut id = "selectAll" expression =
"execution(* com.test.*.*(..))"/>

<aop:before pointcut-ref = "selectAll" method = "beforeAdvice"/>


<aop:after pointcut-ref = "selectAll" method = "afterAdvice"/>

11 | P a g e
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

<aop:after-returning pointcut-ref = "selectAll"


returning = "retVal" method = "afterReturningAdvice"/>

<aop:after-throwing pointcut-ref = "selectAll"


throwing = "ex" method = "AfterThrowingAdvice"/>
</aop:aspect>
</aop:config>

<!-- Definition for student bean -->


<bean id = "student" class = "com.tutorialspoint.Student">
<property name = "name" value = "Zara" />
<property name = "age" value = "11"/>
</bean>

<!-- Definition for logging aspect -->


<bean id = "logging" class = "com.tutorialspoint.Logging"/>

</beans>

12 | P a g e
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

Steps For Developing An @AspectJ based Application

@AspectJ refers to a style of declaring aspects as regular Java classes annotated


with Java 5 annotations.

1. Create a project with a name SpringExample and create a package com.test under the
src folder in the created project.

2. Add required Spring libraries using Add External JARs option.

3. Add Spring AOP specific libraries aspectjrt.jar, aspectjweaver.jar and aspectj.jar.

4. Create Java classes Logging, Student and MainApp under the com.test package.

5. Create Beans configuration file Beans.xml under the src folder.

6. The final step is to create the content of all the Java files and Bean Configuration file
and run the application.

Here is the content of Logging.java file. This is actually a sample of aspect module which
defines methods to be called at various points.

import org.aspectj.lang.annotation.*;

@Aspect public class


Logging {
//Following is the definition for a pointcut to select all the methods available. So advice will
//be called for all the methods.
@Pointcut("execution(* com.test.*.*(..))")
private void selectAll(){}

//This is the method which I would like to execute before a selected method execution.

13 | P a g e
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

@Before("selectAll()")
public void beforeAdvice(){
System.out.println("Going to setup student profile.");
}

//This is the method which I would like to execute after a selected method execution.

@After("selectAll()")
public void afterAdvice(){
System.out.println("Student profile has been setup.");
}
//This is the method which I would like to execute when any method returns.

@AfterReturning(pointcut = "selectAll()", returning = "retVal")


public void afterReturningAdvice(Object retVal){
System.out.println("Returning:" + retVal.toString() );
}

//This is the method which I would like to execute if there is an exception raised by any
//method.

@AfterThrowing(pointcut = "selectAll()", throwing = "ex")


public void AfterThrowingAdvice(IllegalArgumentException ex){
System.out.println("There has been an exception: " + ex.toString());
}
}

Following is the content of the Student.java file

public class Student {


private Integer age;
private String name;

14 | P a g e
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

public void setAge(Integer age) {


this.age = age;
}
public Integer getAge() {
System.out.println("Age : " + age );
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
System.out.println("Name : " + name );
return name;
}
public void printThrowException(){
System.out.println("Exception raised"); throw
new IllegalArgumentException();
}
}

Following is the content of the MainApp.java file

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Student student = (Student) context.getBean("student"); student.getName();
student.getAge();

student.printThrowException();
}

15 | P a g e
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab, Mumbai,
Maharashtra 400604
Developed by:- Prof Abhay More

}
Following is the configuration file Beans.xml

<?xml version = "1.0" encoding = "UTF-8"?>


<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:aop
= "http://www.springframework.org/schema/aop" xsi:schemaLocation =
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

<aop:aspectj-autoproxy/>

<!-- Definition for student bean -->


<bean id = "student" class = "com.test.Student">
<property name = "name" value = "Zara" />
<property name = "age" value = "11"/>
</bean>

<!-- Definition for logging aspect -->


<bean id = "logging" class = "com.test.Logging"/>

</beans>

16 | P a g e

You might also like