美文网首页
Spring基于XML文件的方式配置AOP

Spring基于XML文件的方式配置AOP

作者: BlueSkyBlue | 来源:发表于2020-03-19 20:05 被阅读0次

除了使用注解的方式配置切面,我们还可以使用XML文件的方式配置。

使用XML文件配置AOP

  1. 编写切面逻辑
public class LoggingAspect {

    public void beforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        Object [] args = joinPoint.getArgs();
        System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
    }

    public void afterMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " ends.");
    }

    public void afterReturning(JoinPoint joinPoint, Object result){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " ends with " + 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){

        String methodName = pjd.getSignature().getName();
        Object result = null;
        try {
            System.out.println("The method name " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));
            result = pjd.proceed();
            System.out.println("The method name " + methodName + " ends with " + result);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result;
    }
}
  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);
}
  1. 编写目标方法
public class ArithmaticCalculatorLoggingImpl implements ArithmeticCalculator {
    @Override
    public int add(int i, int j) {
        int result = i + j;
        return result;
    }

    @Override
    public int sub(int i, int j) {
        int result = i - j;
        return result;
    }

    @Override
    public int mul(int i, int j) {
        int result = i * j;
        return result;
    }

    @Override
    public int div(int i, int j) {
        int result = i / j;
        return result;
    }
}
  1. 在XML文件中定义bean
<bean id="arithmeticCalculator"
      class="com.spring.xml.ArithmaticCalculatorLoggingImpl"></bean>

<bean id="loggingAspect"
      class="com.spring.xml.LoggingAspect"></bean>
  1. 在XML文件中定义切入点和具体操作
<aop:config>
    <aop:pointcut id="pointcut"
          expression="execution(public int com.spring.xml.ArithmeticCalculator.*(..))"></aop:pointcut>
    <aop:aspect ref="loggingAspect">
        <aop:before method="beforeMethod" pointcut-ref="pointcut"></aop:before>
    </aop:aspect>
</aop:config>

相关文章

网友评论

      本文标题:Spring基于XML文件的方式配置AOP

      本文链接:https://www.haomeiwen.com/subject/jvxryhtx.html