步骤
此处导包和在配置文件中加入命名空间同上篇一样,不在赘述
1.编写目标类
public interface ArithmeticCalculator {
int add(int i, int j);
int sub(int i, int j);
int mul(int i, int j);
int div(int i,int j);
}
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
public int add(int i, int j) {
int result = i+ j;
return result;
}
public int sub(int i, int j) {
int result = i - j;
return result;
}
public int mul(int i, int j) {
int result = i * j;
return result;
}
public int div(int i, int j) {
int result = i / j;
return result;
}
}
2.配置目标类
<bean id="arithmeticCalculator" class="com.atguigu.spring.aop.xml.ArithmeticCalculatorImpl"></bean>
3.编写切入类
public class LoggingAspect {
public void beforeMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method "+ methodName +" begins with" + args);
}
public void afterMethod(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method "+ methodName +" end ");
}
public void afterReturning(JoinPoint joinPoint,Object result) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName+ " end result:" + result);
}
public void afterThrowing(JoinPoint joinPoint,Exception ex) {
String methodName = joinPoint.getSignature().getName();
System.out.println("The method " + methodName +" occurs exception:" + ex );
}
public Object aroundMethod(ProceedingJoinPoint pjd) {
Object result = null;
String methodName = pjd.getSignature().getName();
//执行方法
try {
//前置通知
System.out.println("The method " + methodName+ " begins with" + Arrays.asList(pjd.getArgs()));
result = pjd.proceed();
//返回通知
System.out.println("The method " + methodName + " end with:" + result);
} catch (Throwable e) {
System.out.println("The method " + methodName + " occurs exception:" + e);
}
System.out.println("The method " + methodName + " ends ");
return 100;
}
}
public class VlidationAspect {
public void validataArgs(JoinPoint joinPoint) {
System.out.println("--->validate:" +Arrays.asList(joinPoint.getArgs()));
}
}
4.配置切面类
<bean id="loggingAspect" class="com.atguigu.spring.aop.xml.LoggingAspect"></bean>
<bean id= "vlidationAspect" class="com.atguigu.spring.aop.xml.VlidationAspect"></bean>
5.进行AOP配置
<aop:config>
<!-- 配置切点表达式 -->
<aop:pointcut expression="execution(* com.atgui.spring.aop.xml.*.*(..))" id="pointcut"/>
<!-- 配置切面及通知 -->
<aop:aspect ref="loggingAspect" order="2">
<aop:before method="beforeMethod" pointcut-ref="poincut"/>
<aop:after method="afterMethod" pointcut-ref="pointcut"/>
<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="ex"/>
<aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>
<aop:around method="aroundMethod" pointcut-ref="pointcut"/>
</aop:aspect>
<aop:aspect ref="vlidationAspect" order="1">
<aop:before method="validataArgs" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>