Introduction to Aspects
Posted by Iroshan at 11:36 AM on 21, Oct 2009
Application-context.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-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<aop:aspectj-autoproxy />
<bean name="firstAspect"/>
<bean name="helloWorld"/>
</beans>
FirstAspect.java
package com.iroshan.aop.aspects;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class FirstAspect {
@Pointcut("execution(* sayHello(..))")
public void helloPointCut(){
}
@Before("helloPointCut()")
public void helloAdvice(){
System.out.println("Hello There!!!");
}
@Around("helloPointCut()")
public Object helloAroundAdvice(ProceedingJoinPoint pjp) throws Throwable{
Object retVal = pjp.proceed();
System.out.println(retVal);
return 2;
}
}
HelloWorld.java
package com.iroshan.aop;
public class HelloWorld {
public int sayHello() {
System.out.println("Hello World");
return 1;
}
}
Main.java
package com.iroshan.aop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext factory = new ClassPathXmlApplicationContext("Application-context.xml");
HelloWorld helloWorld = (HelloWorld) factory.getBean("helloWorld");
System.out.println(helloWorld.sayHello());
}
}