Spring AOP前置通知、后置通知
- 创建前置通知类、后置通知类,实现MethodBeforeAdvice接口
public class MyBeforeAdvice implements MethodBeforeAdvice {
@Override
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
System.out.println("arg0" + arg0);
System.out.println("arg1" + arg1);
System.out.println("arg2" + arg2);
System.out.println("执行前置通知 before advice");
}
}
/**
* 后置通知类
* @author Small
*
*/
public class MyAfterAdvice implements AfterReturningAdvice {
@Override
public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
System.out.println("执行后置通知");
}
}
2.编写xml文件
<bean id="before" class="com.nancy.test.MyBeforeAdvice"></bean>
<bean id="after" class="com.nancy.test.MyAfterAdvice"></bean>
<aop:config>
<!-- * 匹配任意包 -->
<aop:pointcut expression="execution(* com.nancy.test.Demo.demo2())" id="mypoint"/>
<aop:advisor advice-ref="before" pointcut-ref="mypoint"/>
<aop:advisor advice-ref="after" pointcut-ref="mypoint"/>
</aop:config>
<bean id="demo" class="com.nancy.test.Demo"></bean>
3.测试
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Demo demo = ac.getBean("demo",Demo.class);
demo.demo1();
demo.demo2();
demo.demo3();
}
}
Spring AOP异常通知
1.新建异常类
public class MyThrowAdvice implements ThrowsAdvice{
public void myexception() {
System.out.println("执行异常通知");
}
}
- xml配置
<bean id="throw" class="com.nancy.test.MyThrowAdvice"></bean>
<bean id="demo" class="com.nancy.test.Demo"></bean>
<aop:config>
<aop:aspect ref="throw">
<aop:pointcut expression="execution(* com.nancy.test.Demo.demo2())" id="mypoint"/>
<aop:after-throwing method="myexception" pointcut-ref="mypoint"/>
</aop:aspect>
</aop:config>
环绕通知–注解方式
通知设置:
@Component
@Aspect
public class MyAdvice {
@AfterThrowing("com.nancy.test.Demo.demo1()")
public void mythrow() {
System.out.println("异常通知");
}
@Around("com.nancy.test.Demo.demo1()")
public Object myaround(ProceedingJoinPoint p) throws Throwable {
System.out.println("环绕前置");
Object result = p.proceed();
System.out.println("环绕后置");
return result;
}
}
切点设置:
@Component
public class Demo {
@Pointcut("execution(* com.nancy.test.Demo.demo1())")
// public void demo1(String name,int age) {
// System.out.println("demo1 name: "+name+",age: " + age);
// }
public void demo1() {
System.out.println("demo1 test");
}
}
xml配置:
<context:component-scan base-package="com.nancy.advice,com.nancy.test"></context:component-scan>
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>