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 (often termed crosscutting concerns).
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.
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.
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>
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");
}
}