The
AspectJ Before Advice is applied before the actual business logic method. You
can perform any operation here such as conversion, authentication etc.
Create
a class that contains actual business logic.
Employee.java
==========
package
com.mohan;
public class Employee{
public void
msg(){System.out.println("msg method invoked");}
public int m(){System.out.println("m
method invoked");return 2;}
public int k(){System.out.println("k
method invoked");return 3;}
}
Now,
create the aspect class that contains before advice.
TrackEmployee.java
=============
package
com.mohan;
import
org.aspectj.lang.JoinPoint;
import
org.aspectj.lang.annotation.Aspect;
import
org.aspectj.lang.annotation.Before;
import
org.aspectj.lang.annotation.Pointcut;
@Aspect
public
class TrackEmployee{
@Pointcut("execution(*
Employee.k*(..))")
public void k(){}//pointcut name
@Before("k()")//applying pointcut
on before advice
public void myadvice(JoinPoint jp)//it is
advice (before advice)
{
System.out.println("additional
concern");
}
}
Now
create the Beans.xml file that defines beans.
Beans.xml
=======
<?xml
version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="empBean"
class="com.mohan.Employee">
</bean>
<bean id="trackEmp"
class="com.mohan.TrackEmployee"></bean>
<bean
class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"></bean>
</beans>
Now,
let's call the actual method.
Test.java
======
package
com.mohan;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public
class Test{
public static void main(String[]
args){
ApplicationContext context = new
ClassPathXmlApplicationContext("Beans.xml");
Employee e = (Employee)
context.getBean("empBean");
System.out.println("calling
msg...");
e.msg();
System.out.println("calling
m...");
e.m();
System.out.println("calling
k...");
e.k();
}
}
Expected Output
calling
msg...
additional
concern
msg()
method invoked
calling
m...
additional
concern
m()
method invoked
calling
k...
additional
concern
k()
method invoked
No comments:
Post a Comment