SlideShare a Scribd company logo
Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid
1
Aspect Oriented Programming(AOP):
Before we start Learning AOP, first let’s review other programming paradigms: Functional Programming
and Object Oriented Programming.
1. Functional Programming:
In older programming language like C, we have used functional programming style. In this programming
model, software designers tend to use Top-Down approach, in which the overall objective of the system is
defined first. Then the system is divided into various sub tasks or sub modules. With this methodology,
software development is done by writing a set of sub programs, called functions that can be integrated
together to form a complex system.
In functional programming, the primary focus is on functions. A function is a sub program that performs
a specific task using the values given to it through input variables (called parameters) and then returns
the result to its calling function. Dividing the program into functions is the key to functional programming,
so a number of different functions are written in order to accomplish the tasks. The main problem in this
style of programming is complexity, it is very messy style of coding to write big project programming. In
this approach, very little attention is given to data used by the function. As most of the functions share
global data, they move independently around the system from function to function, thus making the
program vulnerable.
Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid
2
2. Object Oriented Programming(OOP):
Object oriented programming is a programming approach that focuses on data rather than the
algorithm. In this style of programming we would not think about function when we trying to solve
problem, we would think as individual entities as object. Objects are data structures that contain data,
in the form of fields (or attributes) and codes in the form of procedures (or methods). These object interact
with each other by sending messages.
Systems are composed of several components, each responsible for a specific piece of functionality. But
often these components also carry additional responsibilities beyond their core functionality. System
services such as logging, transaction management, and security often find their way into components
whose core responsibilities is something else. These system services are commonly referred to as cross-
cutting concerns because they tend to cut across multiple components in a system.
Let’s try solve the above problem with OOP, the first solution that come to mind is; putting logMessage
method in every object but this is not a good idea for the above problem, because logMessage method is
Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid
3
repeating in each class. Another better solution is creating a Logger class and putting logMessage mothed
in it, now whichever object requires this functionality, can call the Logger object:
But we still have Problems with above approach:
 We still need to write the code in all the methods to call the logger object logMessage(). Any changes
in future will require changes in all method.
 Too many relationship (while designing) with the Logger class which actually doesn’t have any
business logic or is not important.
So, OOP has given us tools to reduce software complexity by introducing concepts like inheritance,
abstraction, and polymorphism. However, developers face daily problems like cross-cutting concerns in
software design that can't be solved easily using OOP. Aspect-Oriented Programming (AOP) tries to solve
these problems by introducing the concept of separation of concerns, in which concerns can be
implemented in a modular and well-localized way.
3. Aspect Oriented Programming(AOP):
Aspect-Oriented Programming (AOP) complements Object-Oriented Programming by providing another
way of thinking about program structure. It was built as a response to limitations of OOP. AOP is often
defined as a technique that promotes separation of program logic into distinct parts (concerns) in a
software system. Today, multiple AOP frameworks are available. AspectJ and SpringAOP are two
dynamics, lightweight and high-performant AOP framework for Java. Spring AOP’s aim is to provide a
close integration between AOP implementation and Spring IoC to help solve common problems in
enterprise applications. Spring provides support for using AspectJ annotations to create aspects.
Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid
4
Enabling AspectJ Annotations with Spring:
With Spring, you can declare advice using AspectJ annotations, but you must first apply the
@EnableAspectJAutoProxy annotation to your configuration class, which will enable support for
handling components marked with AspectJ’s @Aspect annotation:
@Configuration
@ComponentScan(basePackages = . . .})
@EnableAspectJAutoProxy
public class TestConfig {
...
}
AOP Terminologies:
Before we start working with AOP, let us become familiar with the AOP concepts and terminology. These
terms are not specific to Spring, rather they are related to AOP.
Aspect:
The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect.
aspect 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. In Spring AOP, aspects are implemented using regular classes (the schema-based
approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style).
@Aspect
public class LoggingAspect {
. . .
}
Join point:
A Join Point is a point in the execution of the application where an aspect can be plugged in. This point
could be a method being called, an exception being thrown, or even a field being modified.
Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid
5
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. In Spring, an Advice is
modeled as an interceptor, maintaining a chain of interceptors around the Joinpoint. Advice is the
implementation of Aspect. We have 5 type of advices: Before, After, AfterReturning, AfterThrowing and
Around.
@Aspect
public class LoggingAspect {
//Advice
public void logBefore(…) {
. . .
}
}
Pointcut
Pointcuts are expressions that are matched with Join points to determine whether advice needs
to be executed or not. Advice is associated with a pointcut expression and runs at any join point
matched by the pointcut. A pointcut expression starts with a pointcut designator (PCD), which is a
keyword telling Spring AOP what to match. There are several pointcut designators, such as:
@execution, @within, @args, @annotation and @target.
Example1: " execution(public String com.soshiant.service.UserService.getUsersList())"
This pointcut will match exactly the execution of getUsersList method of the UserService class.
Example2: "execution(public String getName())"
This pointcut means, the advice will execute for any Spring Bean method with signature public
String getName().
Example3: "execution(* com.soshiant.service.*.get*())"
This pointcut means, the advice will be applied for all the classes in com.soshiant.service
package whose name starts with get and doesn’t take any arguments.
Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid
6
Example4: "execution(public**(..))"
This pointcust will be applied on all the public methods.
Example5: "within(com.soshiant.service..*)"
This pointcust will be applied on all Types within the service package.
Note: Sometimes we have to use same Pointcut expression at multiple places, we can create an empty
method with @Pointcut annotation and then use it as expression in advices.
Example4:
//Pointcut to execute on all the methods of classes in a package
@Pointcut("execution(* com.soshiant.service.*.get*()")
public void allMethodsPointcut(){
}
Introduction
An Introduction allows adding new methods or attributes to existing classes. The new method and
instance variable can be introduced to existing classes without having to change them, giving them new
state and behavior. Spring AOP allows you to introduce new interfaces (and a corresponding
implementation) to any advised object.
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.
Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid
7
Weaving
Weaving is the process of applying aspects to a target object to create a new proxied 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.
Type of of advices:
 Before Advice: it executes before a method execution (join point method). We can use @Before
annotation to mark an advice type as Before advice. The string parameter passed in the @Before
annotation is the Pointcut expression
Example1:
@Before(execution(public String getName()))
public void logGetNameMethods(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
logger.info("Before " + methodName);
}
In the above example, logGetNameMethods() advice will execute for any Spring Bean method with
signature public String getName().
Example2:
@Before(execution(* com.soshiant.service.*.get*()))
public void logAllGetMethods(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
logger.info("Before " + methodName);
}
In the above example, logAllGetMethods() will be applied for all the classes in
com.soshiant.service package whose name starts with get and doesn’t take any arguments.
Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid
8
 After Advice(finally): it executes after a method execution (join point) regardless of its
outcome (regardless of join point exit whether normally or exceptional return). We can use @After
annotation to mark an advice type as Before advice.
 After Returning Advice: it executes after a method execution (joint point), only if it completes
successfully. We can use @AfterReturning annotation to mark an advice type as Before advice.
 After Throwing Advice: it executes if method exits by throwing an exception. We can use
@AfterThrowing annotation to mark an advice type as Before advice.
 Around Advice: It executes before and after a join point. We can use @Around annotation to
mark an advice type as Before advice.
Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid
9
Spring AOP Example:
In this example, we will add logging aspect to our spring application. Let’s start by adding Spring’s AOP
library dependency in the pom.xml:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${version.spring-framework}</version>
</dependency>
If you are using Spring boot:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>${version.springboot}</version>
</dependency>
Add AspectJ dependency in pom.xml:
<dependency>
<groupId>org.aspectj </groupId>
<artifactId>aspectjrt</artifactId>
<version>${version. aspectj}</version>
</dependency>
<dependency>
<groupId>org.aspectj </groupId>
<artifactId>aspectjweaver</artifactId>
<version>${version.aspectj}</version>
</dependency>
User Model:
public class UserInfo implements java.io.Serializable {
private String userFirstName;
private String userLastName;
private String username;
private String password;
}
Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid
10
User Service:
public interface UserService {
public boolean saveNewUser(UserInfo userInfo);
public List<UserInfo> getUsersList();
}
User ServiceImpl:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public boolean saveNewUser(UserInfo userInfo) {
userDao.saveNewUser(userInfo);
return true;
}
public List<UserInfo> getUsersList(){
List<UserInfo> userInfoList = userDao.getAllUsers();
return userInfoList;
}
}
LoggingAspect:
@Aspect
public class LoggingAspect {
@Before("execution(*com.soshiant.service.users.
UserServiceImpl.addNewUser(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("LoggingAspect.logBefore() is running!");
System.out.println("Method Name : " +
joinPoint.getSignature().getName());
}
}
Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid
11
Above Example on Github:
h ps://github.com/ghorbanihamid/SpringMVC5_AOP_Example
https://github.com/ghorbanihamid/SpringBoot_AOP_JPA_Example
Resources:
https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop
http://jonasboner.com/real-world-scala-managing-cross-cutting-concerns-using-mixin-composition-and-aop/
https://www.javatpoint.com/spring-aop-tutorial
http://www.baeldung.com/spring-aop
https://www.tutorialspoint.com/spring/aop_with_spring.htm
https://djcodes.wordpress.com/frameworks/spring-aop-basics/
https://www.dineshonjava.com/introduction-to-aop-in-spring/
https://howtodoinjava.com/spring/spring-aop/spring-aop-aspectj-example-tutorial-using-annotation-config/

More Related Content

What's hot

Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
Dzmitry Naskou
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
Rasheed Waraich
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Serhat Can
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
Alex Movila
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
Lhouceine OUHAMZA
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Arjun Thakur
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
Knoldus Inc.
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Pei-Tang Huang
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Gunith Devasurendra
 
WTF is Reactive Programming
WTF is Reactive ProgrammingWTF is Reactive Programming
WTF is Reactive Programming
Evgeny Poberezkin
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
Joshua Long
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
Rob Eisenberg
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
Josué Neis
 
Spring Boot
Spring BootSpring Boot
Spring Boot
koppenolski
 
Spring boot
Spring bootSpring boot
Spring boot
sdeeg
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
LivePerson
 
Spring boot
Spring bootSpring boot
Spring boot
Bhagwat Kumar
 

What's hot (20)

Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Spring framework aop
Spring framework aopSpring framework aop
Spring framework aop
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
 
WTF is Reactive Programming
WTF is Reactive ProgrammingWTF is Reactive Programming
WTF is Reactive Programming
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring boot
Spring bootSpring boot
Spring boot
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Spring boot
Spring bootSpring boot
Spring boot
 

Similar to Spring aop

spring aop
spring aopspring aop
spring aop
Kalyani Patil
 
Aspect Oriented Software Development
Aspect Oriented Software DevelopmentAspect Oriented Software Development
Aspect Oriented Software DevelopmentJignesh Patel
 
502 Object Oriented Analysis and Design.pdf
502 Object Oriented Analysis and Design.pdf502 Object Oriented Analysis and Design.pdf
502 Object Oriented Analysis and Design.pdf
PradeepPandey506579
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Akhil Mittal
 
AOP
AOPAOP
ASPECT ORIENTED PROGRAMING(aop)
ASPECT ORIENTED PROGRAMING(aop)ASPECT ORIENTED PROGRAMING(aop)
ASPECT ORIENTED PROGRAMING(aop)
kvsrteja
 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOP
Hitesh-Java
 
Session 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOPSession 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOP
PawanMM
 
Designing function families and bundles with java's behaviors parameterisatio...
Designing function families and bundles with java's behaviors parameterisatio...Designing function families and bundles with java's behaviors parameterisatio...
Designing function families and bundles with java's behaviors parameterisatio...
Alain Lompo
 
Spring aop
Spring aopSpring aop
Spring aop
Harshit Choudhary
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
Shreya Chatterjee
 
Unit-1_Notes(OOAD).pdf
Unit-1_Notes(OOAD).pdfUnit-1_Notes(OOAD).pdf
Unit-1_Notes(OOAD).pdf
ganeshkarthy
 
Object Oriented Approach for Software Development
Object Oriented Approach for Software DevelopmentObject Oriented Approach for Software Development
Object Oriented Approach for Software Development
Rishabh Soni
 
Spring Framework Tutorial | VirtualNuggets
Spring Framework Tutorial | VirtualNuggetsSpring Framework Tutorial | VirtualNuggets
Spring Framework Tutorial | VirtualNuggets
Virtual Nuggets
 
Spring AOP in Nutshell
Spring AOP in Nutshell Spring AOP in Nutshell
Spring AOP in Nutshell
Onkar Deshpande
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
NexThoughts Technologies
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Steven Smith
 
Sdlc
SdlcSdlc
Sdlc
SdlcSdlc
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
deonpmeyer
 

Similar to Spring aop (20)

spring aop
spring aopspring aop
spring aop
 
Aspect Oriented Software Development
Aspect Oriented Software DevelopmentAspect Oriented Software Development
Aspect Oriented Software Development
 
502 Object Oriented Analysis and Design.pdf
502 Object Oriented Analysis and Design.pdf502 Object Oriented Analysis and Design.pdf
502 Object Oriented Analysis and Design.pdf
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
 
AOP
AOPAOP
AOP
 
ASPECT ORIENTED PROGRAMING(aop)
ASPECT ORIENTED PROGRAMING(aop)ASPECT ORIENTED PROGRAMING(aop)
ASPECT ORIENTED PROGRAMING(aop)
 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOP
 
Session 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOPSession 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOP
 
Designing function families and bundles with java's behaviors parameterisatio...
Designing function families and bundles with java's behaviors parameterisatio...Designing function families and bundles with java's behaviors parameterisatio...
Designing function families and bundles with java's behaviors parameterisatio...
 
Spring aop
Spring aopSpring aop
Spring aop
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
 
Unit-1_Notes(OOAD).pdf
Unit-1_Notes(OOAD).pdfUnit-1_Notes(OOAD).pdf
Unit-1_Notes(OOAD).pdf
 
Object Oriented Approach for Software Development
Object Oriented Approach for Software DevelopmentObject Oriented Approach for Software Development
Object Oriented Approach for Software Development
 
Spring Framework Tutorial | VirtualNuggets
Spring Framework Tutorial | VirtualNuggetsSpring Framework Tutorial | VirtualNuggets
Spring Framework Tutorial | VirtualNuggets
 
Spring AOP in Nutshell
Spring AOP in Nutshell Spring AOP in Nutshell
Spring AOP in Nutshell
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
 
Sdlc
SdlcSdlc
Sdlc
 
Sdlc
SdlcSdlc
Sdlc
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 

More from Hamid Ghorbani

Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
Hamid Ghorbani
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
Hamid Ghorbani
 
Payment Tokenization
Payment TokenizationPayment Tokenization
Payment Tokenization
Hamid Ghorbani
 
Reactjs Basics
Reactjs BasicsReactjs Basics
Reactjs Basics
Hamid Ghorbani
 
Rest web service
Rest web serviceRest web service
Rest web service
Hamid Ghorbani
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
Hamid Ghorbani
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Java Threads
Java ThreadsJava Threads
Java Threads
Hamid Ghorbani
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
Hamid Ghorbani
 
Java Generics
Java GenericsJava Generics
Java Generics
Hamid Ghorbani
 
Java collections
Java collectionsJava collections
Java collections
Hamid Ghorbani
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
Hamid Ghorbani
 
IBM Integeration Bus(IIB) Fundamentals
IBM Integeration Bus(IIB) FundamentalsIBM Integeration Bus(IIB) Fundamentals
IBM Integeration Bus(IIB) Fundamentals
Hamid Ghorbani
 
ESB Overview
ESB OverviewESB Overview
ESB Overview
Hamid Ghorbani
 
Spring security configuration
Spring security configurationSpring security configuration
Spring security configuration
Hamid Ghorbani
 
SOA & ESB in banking systems(Persian language)
SOA & ESB in banking systems(Persian language)SOA & ESB in banking systems(Persian language)
SOA & ESB in banking systems(Persian language)
Hamid Ghorbani
 

More from Hamid Ghorbani (16)

Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Payment Tokenization
Payment TokenizationPayment Tokenization
Payment Tokenization
 
Reactjs Basics
Reactjs BasicsReactjs Basics
Reactjs Basics
 
Rest web service
Rest web serviceRest web service
Rest web service
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java collections
Java collectionsJava collections
Java collections
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
IBM Integeration Bus(IIB) Fundamentals
IBM Integeration Bus(IIB) FundamentalsIBM Integeration Bus(IIB) Fundamentals
IBM Integeration Bus(IIB) Fundamentals
 
ESB Overview
ESB OverviewESB Overview
ESB Overview
 
Spring security configuration
Spring security configurationSpring security configuration
Spring security configuration
 
SOA & ESB in banking systems(Persian language)
SOA & ESB in banking systems(Persian language)SOA & ESB in banking systems(Persian language)
SOA & ESB in banking systems(Persian language)
 

Recently uploaded

Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 

Recently uploaded (20)

Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 

Spring aop

  • 1. Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid 1 Aspect Oriented Programming(AOP): Before we start Learning AOP, first let’s review other programming paradigms: Functional Programming and Object Oriented Programming. 1. Functional Programming: In older programming language like C, we have used functional programming style. In this programming model, software designers tend to use Top-Down approach, in which the overall objective of the system is defined first. Then the system is divided into various sub tasks or sub modules. With this methodology, software development is done by writing a set of sub programs, called functions that can be integrated together to form a complex system. In functional programming, the primary focus is on functions. A function is a sub program that performs a specific task using the values given to it through input variables (called parameters) and then returns the result to its calling function. Dividing the program into functions is the key to functional programming, so a number of different functions are written in order to accomplish the tasks. The main problem in this style of programming is complexity, it is very messy style of coding to write big project programming. In this approach, very little attention is given to data used by the function. As most of the functions share global data, they move independently around the system from function to function, thus making the program vulnerable.
  • 2. Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid 2 2. Object Oriented Programming(OOP): Object oriented programming is a programming approach that focuses on data rather than the algorithm. In this style of programming we would not think about function when we trying to solve problem, we would think as individual entities as object. Objects are data structures that contain data, in the form of fields (or attributes) and codes in the form of procedures (or methods). These object interact with each other by sending messages. Systems are composed of several components, each responsible for a specific piece of functionality. But often these components also carry additional responsibilities beyond their core functionality. System services such as logging, transaction management, and security often find their way into components whose core responsibilities is something else. These system services are commonly referred to as cross- cutting concerns because they tend to cut across multiple components in a system. Let’s try solve the above problem with OOP, the first solution that come to mind is; putting logMessage method in every object but this is not a good idea for the above problem, because logMessage method is
  • 3. Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid 3 repeating in each class. Another better solution is creating a Logger class and putting logMessage mothed in it, now whichever object requires this functionality, can call the Logger object: But we still have Problems with above approach:  We still need to write the code in all the methods to call the logger object logMessage(). Any changes in future will require changes in all method.  Too many relationship (while designing) with the Logger class which actually doesn’t have any business logic or is not important. So, OOP has given us tools to reduce software complexity by introducing concepts like inheritance, abstraction, and polymorphism. However, developers face daily problems like cross-cutting concerns in software design that can't be solved easily using OOP. Aspect-Oriented Programming (AOP) tries to solve these problems by introducing the concept of separation of concerns, in which concerns can be implemented in a modular and well-localized way. 3. Aspect Oriented Programming(AOP): Aspect-Oriented Programming (AOP) complements Object-Oriented Programming by providing another way of thinking about program structure. It was built as a response to limitations of OOP. AOP is often defined as a technique that promotes separation of program logic into distinct parts (concerns) in a software system. Today, multiple AOP frameworks are available. AspectJ and SpringAOP are two dynamics, lightweight and high-performant AOP framework for Java. Spring AOP’s aim is to provide a close integration between AOP implementation and Spring IoC to help solve common problems in enterprise applications. Spring provides support for using AspectJ annotations to create aspects.
  • 4. Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid 4 Enabling AspectJ Annotations with Spring: With Spring, you can declare advice using AspectJ annotations, but you must first apply the @EnableAspectJAutoProxy annotation to your configuration class, which will enable support for handling components marked with AspectJ’s @Aspect annotation: @Configuration @ComponentScan(basePackages = . . .}) @EnableAspectJAutoProxy public class TestConfig { ... } AOP Terminologies: Before we start working with AOP, let us become familiar with the AOP concepts and terminology. These terms are not specific to Spring, rather they are related to AOP. Aspect: The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. aspect 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. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style). @Aspect public class LoggingAspect { . . . } Join point: A Join Point is a point in the execution of the application where an aspect can be plugged in. This point could be a method being called, an exception being thrown, or even a field being modified.
  • 5. Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid 5 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. In Spring, an Advice is modeled as an interceptor, maintaining a chain of interceptors around the Joinpoint. Advice is the implementation of Aspect. We have 5 type of advices: Before, After, AfterReturning, AfterThrowing and Around. @Aspect public class LoggingAspect { //Advice public void logBefore(…) { . . . } } Pointcut Pointcuts are expressions that are matched with Join points to determine whether advice needs to be executed or not. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut. A pointcut expression starts with a pointcut designator (PCD), which is a keyword telling Spring AOP what to match. There are several pointcut designators, such as: @execution, @within, @args, @annotation and @target. Example1: " execution(public String com.soshiant.service.UserService.getUsersList())" This pointcut will match exactly the execution of getUsersList method of the UserService class. Example2: "execution(public String getName())" This pointcut means, the advice will execute for any Spring Bean method with signature public String getName(). Example3: "execution(* com.soshiant.service.*.get*())" This pointcut means, the advice will be applied for all the classes in com.soshiant.service package whose name starts with get and doesn’t take any arguments.
  • 6. Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid 6 Example4: "execution(public**(..))" This pointcust will be applied on all the public methods. Example5: "within(com.soshiant.service..*)" This pointcust will be applied on all Types within the service package. Note: Sometimes we have to use same Pointcut expression at multiple places, we can create an empty method with @Pointcut annotation and then use it as expression in advices. Example4: //Pointcut to execute on all the methods of classes in a package @Pointcut("execution(* com.soshiant.service.*.get*()") public void allMethodsPointcut(){ } Introduction An Introduction allows adding new methods or attributes to existing classes. The new method and instance variable can be introduced to existing classes without having to change them, giving them new state and behavior. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any advised object. 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.
  • 7. Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid 7 Weaving Weaving is the process of applying aspects to a target object to create a new proxied 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. Type of of advices:  Before Advice: it executes before a method execution (join point method). We can use @Before annotation to mark an advice type as Before advice. The string parameter passed in the @Before annotation is the Pointcut expression Example1: @Before(execution(public String getName())) public void logGetNameMethods(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); logger.info("Before " + methodName); } In the above example, logGetNameMethods() advice will execute for any Spring Bean method with signature public String getName(). Example2: @Before(execution(* com.soshiant.service.*.get*())) public void logAllGetMethods(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); logger.info("Before " + methodName); } In the above example, logAllGetMethods() will be applied for all the classes in com.soshiant.service package whose name starts with get and doesn’t take any arguments.
  • 8. Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid 8  After Advice(finally): it executes after a method execution (join point) regardless of its outcome (regardless of join point exit whether normally or exceptional return). We can use @After annotation to mark an advice type as Before advice.  After Returning Advice: it executes after a method execution (joint point), only if it completes successfully. We can use @AfterReturning annotation to mark an advice type as Before advice.  After Throwing Advice: it executes if method exits by throwing an exception. We can use @AfterThrowing annotation to mark an advice type as Before advice.  Around Advice: It executes before and after a join point. We can use @Around annotation to mark an advice type as Before advice.
  • 9. Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid 9 Spring AOP Example: In this example, we will add logging aspect to our spring application. Let’s start by adding Spring’s AOP library dependency in the pom.xml: <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${version.spring-framework}</version> </dependency> If you are using Spring boot: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> <version>${version.springboot}</version> </dependency> Add AspectJ dependency in pom.xml: <dependency> <groupId>org.aspectj </groupId> <artifactId>aspectjrt</artifactId> <version>${version. aspectj}</version> </dependency> <dependency> <groupId>org.aspectj </groupId> <artifactId>aspectjweaver</artifactId> <version>${version.aspectj}</version> </dependency> User Model: public class UserInfo implements java.io.Serializable { private String userFirstName; private String userLastName; private String username; private String password; }
  • 10. Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid 10 User Service: public interface UserService { public boolean saveNewUser(UserInfo userInfo); public List<UserInfo> getUsersList(); } User ServiceImpl: @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public boolean saveNewUser(UserInfo userInfo) { userDao.saveNewUser(userInfo); return true; } public List<UserInfo> getUsersList(){ List<UserInfo> userInfoList = userDao.getAllUsers(); return userInfoList; } } LoggingAspect: @Aspect public class LoggingAspect { @Before("execution(*com.soshiant.service.users. UserServiceImpl.addNewUser(..))") public void logBefore(JoinPoint joinPoint) { System.out.println("LoggingAspect.logBefore() is running!"); System.out.println("Method Name : " + joinPoint.getSignature().getName()); } }
  • 11. Hamid Ghorbani (Spring AOP) https://ir.linkedin.com/in/ghorbanihamid 11 Above Example on Github: h ps://github.com/ghorbanihamid/SpringMVC5_AOP_Example https://github.com/ghorbanihamid/SpringBoot_AOP_JPA_Example Resources: https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop http://jonasboner.com/real-world-scala-managing-cross-cutting-concerns-using-mixin-composition-and-aop/ https://www.javatpoint.com/spring-aop-tutorial http://www.baeldung.com/spring-aop https://www.tutorialspoint.com/spring/aop_with_spring.htm https://djcodes.wordpress.com/frameworks/spring-aop-basics/ https://www.dineshonjava.com/introduction-to-aop-in-spring/ https://howtodoinjava.com/spring/spring-aop/spring-aop-aspectj-example-tutorial-using-annotation-config/