+91 20 24210201/301 info@genex.co.in

Implementation of Aspect oriented programming

- In spring Aspect enables the modularization of cross cutting concerns.
- Using Aspect code related to implement cross cutting concerns remains outside the normal program structure.
- One of the ways to implement Aspect is by annotating regular classes by @Aspect.
 
Terms in AOP:
1) Join point: Represents method execution.
2) Pointcut: Tells what method is invoked.
3) Advice: Action taken by advice at particular join point.
 
Types of Advices:
a) Before advice: advice that executes before join point.
b) After returning advice: advice that executes after join point completes normally.
c) After throwing advice: advice that executes if method exists by throwing exception.
d) After advice: advice that executes in normal and exceptional exits.
e) Around advice: advice surrounds the join point.
 
Configurations to implement AOP:
(Add in applicationcontext.xml)
- Component scanning of package containing class annoted with @Aspect
  (eg. )
 
Jars :
- aspectjweaver-1.6.12.jar
- aspectjrt-1.6.12.jar
- spring-aop-3.1.2.RELEASE.jar
 
Examples :
 
1) After returning aspect:
package com.example.aspect;
@Aspect
@Component
 public class AfterReturningExample {
 
@Pointcut("execution(com.example.myapp.SystemArchitecture.businessService())")
public void executeMethod() {
}
 
@AfterReturning(pointcut = "executeMethod()", returning = "object")
public void afterReturningMethod(Object object) {
  // Implementation
}
}
 
2) After Aspect
package com.example.aspect;
@Aspect
@Component
 public class AfterAspectExample {
 
@Pointcut("execution(com.example.myapp.SystemArchitecture.businessService())")
public void executeMethod() {
}
 
@After(“executeMethod()”)
public void afterMethod() {
  // Implementation
}
}

3)  Before Aspect
package com.example.aspect;
@Aspect
@Component
 public class BeforeAspectExample {
 
@Pointcut("execution(com.example.myapp.SystemArchitecture.businessService())")
public void executeMethod() {
}
 
@Before("executeMethod()  &&  args(object)")
public void beforeMethod(Object object) {
  // Implementation
}
}
 
4) After throwing Aspect
package com.example.aspect;
@Aspect
@Component
 public class AfterThrowingAspectExample {
 
@AfterThrowing(pointcut = "execution(com.example.myapp.SystemArchitecture.businessService())",
 throwing = "exception")
 public void afterThrowing(JoinPoint joinPoint, Object exception) {
                        //Implementation
            }
}
 
5) Around Aspect
package com.example.aspect;
@Aspect
@Component
 public class AroundAspectExample {
 @Around("execution(com.example.myapp.SystemArchitecture.businessService())")
 public Object aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
                   //before Implementation
                   Object retVal = pjp.proceed();
                   // after implementation
                   return retVal;
    }
}
Comments (0)

Post a comment


Maximum 250 alphanumerals only