Spring AOP实例操作 简单易懂
AOP的功能,不改变源代码可以增强类中的方法 (增强 = 代理)
execution([权限修饰符] [返回值类型] [类全路径] [方法名称] ([参数列表]))
例如:
@Before(value = "execution(* com.minelsg.User.add(..))")
在一个类中,哪些方法可以被增强,那这些方法就称为连接点
@Component
public class User {
public void add() {
System.out.println("add.......");
}
}
@Component
@Aspect //生成代理对象
public class UserProxy {
//前置通知
//@Before注解表示作为前置通知
@Before(value = "execution(* com.minelsg.User.add(..))")
public void before() {
System.out.println("before.....");
}
//执行后通知(最终通知)
@After(value = "execution(* com.minelsg.User.add(..))")
public void after(){
System.out.println("after......");
}
//执行后返回值通知
@AfterReturning(value = "execution(* com.minelsg.User.add(..))")
public void afterReturning(){
System.out.println("AfterReturning.........");
}
//@异常通知
@AfterThrowing(value = "execution(* com.minelsg.User.add(..))")
public void afterThrowing(){
System.out.println("AfterThrowing.........");
}
//@Around环绕通知
@Around(value = "execution(* com.minelsg.User.add(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
System.out.println("环绕之前.........");
//add方法执行
proceedingJoinPoint.proceed();
System.out.println("环绕之后.........");
}
}
public class TestAop {
@Test
public void testAopAnno(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
User user = (User)context.getBean("user");
user.add();
}
}
环绕之前......... before..... add....... AfterReturning......... after...... 环绕之后.........
done~~

浙公网安备 33010602011771号