Spring AOP AspectJ 切面编程
Student类
package com.ann.pojo;
public class Student implements MyInterface {
@Override
public void testMethod() {
int i = 6/0; // 异常通知
System.out.println("好好学习,天天向上!Go!Go!Go!");
}
}
Advice类
package com.ann.advice;
import org.aspectj.lang.ProceedingJoinPoint;
public class MyAdvice {
// 前置通知
public void beforce(){
System.out.println("前置通知我最前~");
}
// 后置通知
public void after(){
System.out.println("后置通知我最后~");
}
// 环绕通知
public Object myRound(ProceedingJoinPoint pjp) throws Throwable {
// 环绕前
System.out.println("环绕前");
// 放行
Object proceed = pjp.proceed();
// 环绕后
System.out.println("环绕后");
return proceed;
}
// 异常通知
public void myThrow(Exception e){
System.out.println("xxxxxx异x常x通x知xxxxxx:"+e.getMessage());
}
}
applicationcontext.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-4.3.xsd">
<!--配置业务类bean-->
<bean id="stu" class="com.ann.pojo.Student"></bean>
<!--配置通知类bean-->
<bean id="adv" class="com.ann.advice.MyAdvice"></bean>
<!--配置aop-->
<aop:config>
<aop:aspect ref="adv">
<!--配置切点-->
<aop:pointcut id="pc" expression="execution(* com.ann.pojo.Student.testMethod())"/>
<aop:before method="beforce" pointcut-ref="pc"></aop:before>
<!--aop:after不包含在try语句中,所以报错依然会执行。aop:after-returning是包含在try语句中。-->
<aop:after method="after" pointcut-ref="pc"></aop:after>
<aop:around method="myRound" pointcut-ref="pc"></aop:around>
<aop:after-throwing method="myThrow" pointcut-ref="pc" throwing="e"></aop:after-throwing>
</aop:aspect>
</aop:config>
</beans>
测试代码
package com.ann.test;
import com.ann.pojo.MyInterface;
import com.ann.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AspectTest {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationcontext.xml");
MyInterface stu = (MyInterface) ac.getBean("stu");
stu.testMethod();
}
}
运行结果: