<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
<bean id="myAspect" class="com.demo.spring.aop.MyAspect" />
<bean id="helloWorld" class="com.demo.spring.test.HelloWorld"/>
</beans>
声明一个切面类 :
package com.demo.spring.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
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 MyAspect {
@Pointcut("execution(* execute(. .)) && target(com.demo.spring.test.HelloWorld)" ) //切入点函数
public void pointcut(){
}
@Before("pointcut()") //前置通知 (Before Advice)
public void beforeExecute(JoinPoint thisJoinPoint){
System.out.println("连接点类型:" + thisJoinPoint.getKind());
System.out.println("代理类名:" + thisJoinPoint.getSourceLocation().getClass().getName());
System.out.println("目标类名:" + thisJoinPoint.getTarget().getClass().getName());
System.out.println("目标函数名:" + thisJoinPoint.getSignature().getName());
System.out.println("参数个数:" + thisJoinPoint.getArgs().length);
System.out.println("Before Advice!");
}
@AfterReturning(pointcut = "pointcut()", returning = "retVal") //返回后通知(After returning Advice)
public void afterExecuet(Object retVal){
System.out.println("返回值为:" + retVal);
}
@AfterThrowing(pointcut = "pointcut()", throwing = "ex") //抛出异常后通知(After Throwing Advice)
public void afterThrowing(Exception ex){
System.out.println("Throwing "+ex);
}
@After("pointcut() && args(arg, . .)") //后通知 (After Advice)
public void afterExecute(Obecjt arg){
System.out.print("参数值为:" + args);
System.out.print("After Advice!");
}
@Around("pointcut()") //环绕通知(Around Advice)
public Object userOperate(ProceedingJoinPoint thisJoinPoint) throws Throwable{
System.out.println("Around Advice!");
return thisJoinPoint.proceed();
}
}
定义一个目标函数:
package com.demo.spring.test;
import org.springframework.context.ApplicationContext;
public class HelloWorld {
public String execute(String message){
System.out.println("Hello " + message + "!");
return "Goodbye " + message;
}
public static void main(String[] args){
//ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ApplicationContext ctx = new FileSystemXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld = (HelloWorld)ctx.getBean("helloWorld");
helloWorld.execute("World");
}
}