SlideShare a Scribd company logo
1 of 30
1
• Lhouceine OUHAMZA
• JAVA / JavaScript engineer
• ouhamza.web.pro@gamil.com
2
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.
3
AOP is mostly used in following cases:
•To provide declarative enterprise services such as
declarative transaction management, logging, and
exception management.
•It allows users to implement custom aspects.
4
In this presentation we will see spring AOP
AspectJ Spring
AOP
JBoss
AOP
AOP implementations are provided by:
5
Spring AOP enables Aspect-Oriented Programming in spring
applications. In AOP, aspects enable the modularization of concerns
such as transaction management, logging or security that cut
across multiple types and objects
6
AOP provides the way to dynamically add the cross-cutting
concern before, after or around the actual logic using
simple pluggable configurations. It makes easy to maintain
code in the present and future as well. You can add/remove
concerns without recompiling complete sourcecode simply
by changing configuration files (if you are applying aspects
suing XML configuration).
7
•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.
8
9
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 throwing advice: Advice to be executed if a method exits by throwing an
exception.
After 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.
10
Spring AOP XML Configuration
Spring AOPAspectJ Annotations
Configuration
We are going to approach both configurations.
11
Spring AOP AspectJ @Before Annotation Example
In this spring aop example, we will learn to use
aspectj @Before annotation. @Before annotated methods run exactly
before the all methods matching with pointcut expression.
In this example, We will create simple spring application, add logging
aspect and then invoke aspect methods based on pointcuts
information passed in @Before annotation.
12
AspectJ @Before Annotation Usage
You can use @Before annotation in below manner.
13
Spring AOP Project structure
14
Spring AOP AspectJ Maven Dependencies
I have added spring core, spring aop and aspectj dependencies.
15
Enable AspectJ Support
In XML config file, you can add aop:aspectj-autoproxy element to
enable @AspectJ annotation support.
<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 ">
<!-- Enable @AspectJ annotation support -->
<aop:aspectj-autoproxy />
<!-- Employee manager -->
<bean id="employeeManager" class="com.howtodoinjava.app.service.impl.EmployeeManagerImpl" />
<!-- Logging Aspect -->
<bean id="loggingAspect" class="com.howtodoinjava.app.aspect.LoggingAspect" />
</beans>
16
Service methods on which aspects needs to be executed (1)
EmployeeManager.java and EmployeeManagerImpl.java
public interface EmployeeManager
{
public EmployeeDTO getEmployeeById(Integer employeeId);
public List<EmployeeDTO> getAllEmployee();
public void createEmployee(EmployeeDTO employee);
public void deleteEmployee(Integer employeeId);
public void updateEmployee(EmployeeDTO employee);
}
17
Service methods on which aspects needs to be executed (2)
public class EmployeeManagerImpl implements EmployeeManager
{
public EmployeeDTO getEmployeeById(Integer employeeId)
{
System.out.println("Method getEmployeeById() called");
return new EmployeeDTO();
}
public List<EmployeeDTO> getAllEmployee()
{
System.out.println("Method getAllEmployee() called");
return new ArrayList<EmployeeDTO>();
}
public void createEmployee(EmployeeDTO employee)
{
System.out.println("Method createEmployee() called");
}
public void deleteEmployee(Integer employeeId)
{
System.out.println("Method deleteEmployee() called");
}
public void updateEmployee(EmployeeDTO employee)
{
System.out.println("Method updateEmployee() called");
}
}
18
Write AspectJ Annotated Class and Methods
Write aspectj annotated class and methods with pointcut information.
@Aspect
public class LoggingAspect {
@Before("execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.*(..))")
public void logBeforeAllMethods(JoinPoint joinPoint)
{
System.out.println("****LoggingAspect.logBeforeAllMethods() : " + joinPoint.getSignature().getName());
}
@Before("execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.getEmployeeById(..))")
public void logBeforeGetEmployee(JoinPoint joinPoint)
{
System.out.println("****LoggingAspect.logBeforeGetEmployee() : " + joinPoint.getSignature().getName());
}
@Before("execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.createEmployee(..))")
public void logBeforeCreateEmployee(JoinPoint joinPoint)
{
System.out.println("****LoggingAspect.logBeforeCreateEmployee() : " + joinPoint.getSignature().getName());
}
}
19
Test Spring AspectJ Configuration and Execution
Now let’s test whether above configured aspects execute on given
pointcut information.
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.howtodoinjava.app.model.EmployeeDTO;
import com.howtodoinjava.app.service.EmployeeManager;
public class TestMain
{
@SuppressWarnings("resource")
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeManager manager = (EmployeeManager) context.getBean("employeeManager");
manager.getEmployeeById(1);
manager.createEmployee(new EmployeeDTO());
}
}
20
Test Spring AspectJ Configuration and Execution
Clearly aspect advices executed on revelant jointpoints.
21
Spring AOP Before Advice Example
In this spring aop example, we will learn to use AOP beforeadvice
using <aop:before/> configuration.
Methods configured as before advice, run immediately before the methods
which match the pointcut expression passed as argument.
In this example, We will create simple spring application, add logging aspect
and then invoke aspect methods based on pointcuts information passed
in <aop:before/> xml configuration.
22
To create a before advice, using xml configuration, use <aop:before/> in below
manner.
<aop:config>
<aop:aspect ref="loggingAspect">
<aop:pointcut expression="execution(*
com.howtodoinjava.app.service.impl.EmployeeManagerImpl.*(..))" id="loggingPointcuts"/>
<!-- before advice -->
<aop:before method="logBeforeAllMethods" pointcut-ref="loggingPointcuts" />
</aop:aspect>
</aop:config>
23
24
I have added spring core, spring aop and aspectj dependencies.
25
In XML config file, you can add aop:config element to add AOP support.
<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 ref="loggingAspect">
<aop:pointcut expression="execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.*(..))"
id="loggingPointcuts"/>
<!-- before advice -->
<aop:before method="logBeforeAllMethods" pointcut-ref="loggingPointcuts" />
</aop:aspect>
</aop:config>
<!-- Employee manager -->
<bean id="employeeManager" class="com.howtodoinjava.app.service.impl.EmployeeManagerImpl" />
<!-- Logging Aspect -->
<bean id="loggingAspect" class="com.howtodoinjava.app.aspect.LoggingAspect" />
</beans>
26
EmployeeManager.java and EmployeeManagerImpl.java
public interface EmployeeManager
{
public EmployeeDTO getEmployeeById(Integer employeeId);
public List<EmployeeDTO> getAllEmployee();
public void createEmployee(EmployeeDTO employee);
public void deleteEmployee(Integer employeeId);
public void updateEmployee(EmployeeDTO employee);
}
27
public class EmployeeManagerImpl implements EmployeeManager
{
public EmployeeDTO getEmployeeById(Integer employeeId)
{
System.out.println("Method getEmployeeById() called");
return new EmployeeDTO();
}
public List<EmployeeDTO> getAllEmployee()
{
System.out.println("Method getAllEmployee() called");
return new ArrayList<EmployeeDTO>();
}
public void createEmployee(EmployeeDTO employee)
{
System.out.println("Method createEmployee() called");
}
public void deleteEmployee(Integer employeeId)
{
System.out.println("Method deleteEmployee() called");
}
public void updateEmployee(EmployeeDTO employee)
{
System.out.println("Method updateEmployee() called");
}
}
28
Write aspect class and methods to be executed as advice.
29
Now let’s test whether above configured aspects execute on given pointcut information.
Clearly aspect
advices executed
on relevant
jointpoints.
30

More Related Content

What's hot

Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesHitesh-Java
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Spring framework IOC and Dependency Injection
Spring framework  IOC and Dependency InjectionSpring framework  IOC and Dependency Injection
Spring framework IOC and Dependency InjectionAnuj Singh Rajput
 
Spring boot anane maryem ben aziza syrine
Spring boot anane maryem ben aziza syrineSpring boot anane maryem ben aziza syrine
Spring boot anane maryem ben aziza syrineSyrine Ben aziza
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications JavaAntoine Rey
 
Spring Meetup Paris - Back to the basics of Spring (Boot)
Spring Meetup Paris - Back to the basics of Spring (Boot)Spring Meetup Paris - Back to the basics of Spring (Boot)
Spring Meetup Paris - Back to the basics of Spring (Boot)Eric SIBER
 
WEB SERVICE SOAP, JAVA, XML, JAXWS
WEB SERVICE SOAP, JAVA, XML, JAXWSWEB SERVICE SOAP, JAVA, XML, JAXWS
WEB SERVICE SOAP, JAVA, XML, JAXWSLhouceine OUHAMZA
 
Spring boot
Spring bootSpring boot
Spring bootsdeeg
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architectureAnurag
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsBG Java EE Course
 

What's hot (20)

Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
Spring AOP in Nutshell
Spring AOP in Nutshell Spring AOP in Nutshell
Spring AOP in Nutshell
 
Spring ioc
Spring iocSpring ioc
Spring ioc
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Spring framework IOC and Dependency Injection
Spring framework  IOC and Dependency InjectionSpring framework  IOC and Dependency Injection
Spring framework IOC and Dependency Injection
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring boot anane maryem ben aziza syrine
Spring boot anane maryem ben aziza syrineSpring boot anane maryem ben aziza syrine
Spring boot anane maryem ben aziza syrine
 
Introduction à JPA (Java Persistence API )
Introduction à JPA  (Java Persistence API )Introduction à JPA  (Java Persistence API )
Introduction à JPA (Java Persistence API )
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications Java
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Meetup Paris - Back to the basics of Spring (Boot)
Spring Meetup Paris - Back to the basics of Spring (Boot)Spring Meetup Paris - Back to the basics of Spring (Boot)
Spring Meetup Paris - Back to the basics of Spring (Boot)
 
WEB SERVICE SOAP, JAVA, XML, JAXWS
WEB SERVICE SOAP, JAVA, XML, JAXWSWEB SERVICE SOAP, JAVA, XML, JAXWS
WEB SERVICE SOAP, JAVA, XML, JAXWS
 
Spring boot
Spring bootSpring boot
Spring boot
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Les collections en Java
Les collections en JavaLes collections en Java
Les collections en Java
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 

Similar to Spring AOP

Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOPHitesh-Java
 
Session 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOPSession 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOPPawanMM
 
Spring aop concepts
Spring aop conceptsSpring aop concepts
Spring aop conceptsRushiBShah
 
Aspect Oriented Programming: Hidden Toolkit That You Already Have
Aspect Oriented Programming: Hidden Toolkit That You Already HaveAspect Oriented Programming: Hidden Toolkit That You Already Have
Aspect Oriented Programming: Hidden Toolkit That You Already HaveSalesforce Engineering
 
Introduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingIntroduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingAmir Kost
 
Spring boot for buidling microservices
Spring boot for buidling microservicesSpring boot for buidling microservices
Spring boot for buidling microservicesNilanjan Roy
 
Metrics by coda hale : to know your app’ health
Metrics by coda hale : to know your app’ healthMetrics by coda hale : to know your app’ health
Metrics by coda hale : to know your app’ healthIzzet Mustafaiev
 
Spring 1 day program
Spring 1 day programSpring 1 day program
Spring 1 day programMohit Kanwar
 
Introduction to Spring
Introduction to SpringIntroduction to Spring
Introduction to SpringSujit Kumar
 
Simplifying RCP Update and Install
Simplifying RCP Update and InstallSimplifying RCP Update and Install
Simplifying RCP Update and Installsusanfmccourt
 
Sap alv excel inplace with macro recording sapignite
Sap alv excel inplace with macro recording sapigniteSap alv excel inplace with macro recording sapignite
Sap alv excel inplace with macro recording sapigniteAromal Raveendran
 
Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6helpido9
 

Similar to Spring AOP (20)

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
 
Spring aop concepts
Spring aop conceptsSpring aop concepts
Spring aop concepts
 
Aspect Oriented Programming: Hidden Toolkit That You Already Have
Aspect Oriented Programming: Hidden Toolkit That You Already HaveAspect Oriented Programming: Hidden Toolkit That You Already Have
Aspect Oriented Programming: Hidden Toolkit That You Already Have
 
spring aop
spring aopspring aop
spring aop
 
Introduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingIntroduction to Aspect Oriented Programming
Introduction to Aspect Oriented Programming
 
Spring aop
Spring aopSpring aop
Spring aop
 
Spring framework part 2
Spring framework  part 2Spring framework  part 2
Spring framework part 2
 
Spring boot for buidling microservices
Spring boot for buidling microservicesSpring boot for buidling microservices
Spring boot for buidling microservices
 
Spring framework AOP
Spring framework  AOPSpring framework  AOP
Spring framework AOP
 
Metrics by coda hale : to know your app’ health
Metrics by coda hale : to know your app’ healthMetrics by coda hale : to know your app’ health
Metrics by coda hale : to know your app’ health
 
Spring 1 day program
Spring 1 day programSpring 1 day program
Spring 1 day program
 
Introduction to Spring
Introduction to SpringIntroduction to Spring
Introduction to Spring
 
Simplifying RCP Update and Install
Simplifying RCP Update and InstallSimplifying RCP Update and Install
Simplifying RCP Update and Install
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
Sap alv excel inplace with macro recording sapignite
Sap alv excel inplace with macro recording sapigniteSap alv excel inplace with macro recording sapignite
Sap alv excel inplace with macro recording sapignite
 
Spring batch
Spring batchSpring batch
Spring batch
 
Workflow for XPages
Workflow for XPagesWorkflow for XPages
Workflow for XPages
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6
 

More from Lhouceine OUHAMZA

More from Lhouceine OUHAMZA (9)

Présentation sur internet.pptx
Présentation sur internet.pptxPrésentation sur internet.pptx
Présentation sur internet.pptx
 
Prometheus and Grafana
Prometheus and GrafanaPrometheus and Grafana
Prometheus and Grafana
 
Kubernetes
KubernetesKubernetes
Kubernetes
 
Scrum course
Scrum courseScrum course
Scrum course
 
Jenkins
JenkinsJenkins
Jenkins
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Extreme Programming (XP)
Extreme Programming (XP)Extreme Programming (XP)
Extreme Programming (XP)
 
Systemes authentification
Systemes authentificationSystemes authentification
Systemes authentification
 
Presentation of framework Angular
Presentation of framework AngularPresentation of framework Angular
Presentation of framework Angular
 

Recently uploaded

Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating SystemRashmi Bhat
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsSachinPawar510423
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESNarmatha D
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
The SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsThe SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsDILIPKUMARMONDAL6
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptMadan Karki
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
Steel Structures - Building technology.pptx
Steel Structures - Building technology.pptxSteel Structures - Building technology.pptx
Steel Structures - Building technology.pptxNikhil Raut
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 

Recently uploaded (20)

Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating System
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documents
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIES
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
The SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsThe SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teams
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.ppt
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
Steel Structures - Building technology.pptx
Steel Structures - Building technology.pptxSteel Structures - Building technology.pptx
Steel Structures - Building technology.pptx
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 

Spring AOP

  • 1. 1 • Lhouceine OUHAMZA • JAVA / JavaScript engineer • ouhamza.web.pro@gamil.com
  • 2. 2 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.
  • 3. 3 AOP is mostly used in following cases: •To provide declarative enterprise services such as declarative transaction management, logging, and exception management. •It allows users to implement custom aspects.
  • 4. 4 In this presentation we will see spring AOP AspectJ Spring AOP JBoss AOP AOP implementations are provided by:
  • 5. 5 Spring AOP enables Aspect-Oriented Programming in spring applications. In AOP, aspects enable the modularization of concerns such as transaction management, logging or security that cut across multiple types and objects
  • 6. 6 AOP provides the way to dynamically add the cross-cutting concern before, after or around the actual logic using simple pluggable configurations. It makes easy to maintain code in the present and future as well. You can add/remove concerns without recompiling complete sourcecode simply by changing configuration files (if you are applying aspects suing XML configuration).
  • 7. 7 •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.
  • 8. 8
  • 9. 9 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 throwing advice: Advice to be executed if a method exits by throwing an exception. After 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.
  • 10. 10 Spring AOP XML Configuration Spring AOPAspectJ Annotations Configuration We are going to approach both configurations.
  • 11. 11 Spring AOP AspectJ @Before Annotation Example In this spring aop example, we will learn to use aspectj @Before annotation. @Before annotated methods run exactly before the all methods matching with pointcut expression. In this example, We will create simple spring application, add logging aspect and then invoke aspect methods based on pointcuts information passed in @Before annotation.
  • 12. 12 AspectJ @Before Annotation Usage You can use @Before annotation in below manner.
  • 14. 14 Spring AOP AspectJ Maven Dependencies I have added spring core, spring aop and aspectj dependencies.
  • 15. 15 Enable AspectJ Support In XML config file, you can add aop:aspectj-autoproxy element to enable @AspectJ annotation support. <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 "> <!-- Enable @AspectJ annotation support --> <aop:aspectj-autoproxy /> <!-- Employee manager --> <bean id="employeeManager" class="com.howtodoinjava.app.service.impl.EmployeeManagerImpl" /> <!-- Logging Aspect --> <bean id="loggingAspect" class="com.howtodoinjava.app.aspect.LoggingAspect" /> </beans>
  • 16. 16 Service methods on which aspects needs to be executed (1) EmployeeManager.java and EmployeeManagerImpl.java public interface EmployeeManager { public EmployeeDTO getEmployeeById(Integer employeeId); public List<EmployeeDTO> getAllEmployee(); public void createEmployee(EmployeeDTO employee); public void deleteEmployee(Integer employeeId); public void updateEmployee(EmployeeDTO employee); }
  • 17. 17 Service methods on which aspects needs to be executed (2) public class EmployeeManagerImpl implements EmployeeManager { public EmployeeDTO getEmployeeById(Integer employeeId) { System.out.println("Method getEmployeeById() called"); return new EmployeeDTO(); } public List<EmployeeDTO> getAllEmployee() { System.out.println("Method getAllEmployee() called"); return new ArrayList<EmployeeDTO>(); } public void createEmployee(EmployeeDTO employee) { System.out.println("Method createEmployee() called"); } public void deleteEmployee(Integer employeeId) { System.out.println("Method deleteEmployee() called"); } public void updateEmployee(EmployeeDTO employee) { System.out.println("Method updateEmployee() called"); } }
  • 18. 18 Write AspectJ Annotated Class and Methods Write aspectj annotated class and methods with pointcut information. @Aspect public class LoggingAspect { @Before("execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.*(..))") public void logBeforeAllMethods(JoinPoint joinPoint) { System.out.println("****LoggingAspect.logBeforeAllMethods() : " + joinPoint.getSignature().getName()); } @Before("execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.getEmployeeById(..))") public void logBeforeGetEmployee(JoinPoint joinPoint) { System.out.println("****LoggingAspect.logBeforeGetEmployee() : " + joinPoint.getSignature().getName()); } @Before("execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.createEmployee(..))") public void logBeforeCreateEmployee(JoinPoint joinPoint) { System.out.println("****LoggingAspect.logBeforeCreateEmployee() : " + joinPoint.getSignature().getName()); } }
  • 19. 19 Test Spring AspectJ Configuration and Execution Now let’s test whether above configured aspects execute on given pointcut information. import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.howtodoinjava.app.model.EmployeeDTO; import com.howtodoinjava.app.service.EmployeeManager; public class TestMain { @SuppressWarnings("resource") public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); EmployeeManager manager = (EmployeeManager) context.getBean("employeeManager"); manager.getEmployeeById(1); manager.createEmployee(new EmployeeDTO()); } }
  • 20. 20 Test Spring AspectJ Configuration and Execution Clearly aspect advices executed on revelant jointpoints.
  • 21. 21 Spring AOP Before Advice Example In this spring aop example, we will learn to use AOP beforeadvice using <aop:before/> configuration. Methods configured as before advice, run immediately before the methods which match the pointcut expression passed as argument. In this example, We will create simple spring application, add logging aspect and then invoke aspect methods based on pointcuts information passed in <aop:before/> xml configuration.
  • 22. 22 To create a before advice, using xml configuration, use <aop:before/> in below manner. <aop:config> <aop:aspect ref="loggingAspect"> <aop:pointcut expression="execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.*(..))" id="loggingPointcuts"/> <!-- before advice --> <aop:before method="logBeforeAllMethods" pointcut-ref="loggingPointcuts" /> </aop:aspect> </aop:config>
  • 23. 23
  • 24. 24 I have added spring core, spring aop and aspectj dependencies.
  • 25. 25 In XML config file, you can add aop:config element to add AOP support. <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 ref="loggingAspect"> <aop:pointcut expression="execution(* com.howtodoinjava.app.service.impl.EmployeeManagerImpl.*(..))" id="loggingPointcuts"/> <!-- before advice --> <aop:before method="logBeforeAllMethods" pointcut-ref="loggingPointcuts" /> </aop:aspect> </aop:config> <!-- Employee manager --> <bean id="employeeManager" class="com.howtodoinjava.app.service.impl.EmployeeManagerImpl" /> <!-- Logging Aspect --> <bean id="loggingAspect" class="com.howtodoinjava.app.aspect.LoggingAspect" /> </beans>
  • 26. 26 EmployeeManager.java and EmployeeManagerImpl.java public interface EmployeeManager { public EmployeeDTO getEmployeeById(Integer employeeId); public List<EmployeeDTO> getAllEmployee(); public void createEmployee(EmployeeDTO employee); public void deleteEmployee(Integer employeeId); public void updateEmployee(EmployeeDTO employee); }
  • 27. 27 public class EmployeeManagerImpl implements EmployeeManager { public EmployeeDTO getEmployeeById(Integer employeeId) { System.out.println("Method getEmployeeById() called"); return new EmployeeDTO(); } public List<EmployeeDTO> getAllEmployee() { System.out.println("Method getAllEmployee() called"); return new ArrayList<EmployeeDTO>(); } public void createEmployee(EmployeeDTO employee) { System.out.println("Method createEmployee() called"); } public void deleteEmployee(Integer employeeId) { System.out.println("Method deleteEmployee() called"); } public void updateEmployee(EmployeeDTO employee) { System.out.println("Method updateEmployee() called"); } }
  • 28. 28 Write aspect class and methods to be executed as advice.
  • 29. 29 Now let’s test whether above configured aspects execute on given pointcut information. Clearly aspect advices executed on relevant jointpoints.
  • 30. 30