在调用方法之前,使用spring AOP调用用户定义的方法

时间:2019-05-30 14:48:04

标签: java spring spring-aop

我正在使用Spring AOP,下面是服务类和方面。 我想在调用multiple()之前先调用assignValues()方法。

package com.test.service;
import org.springframework.stereotype.Service;
@Service
public class MathService {  
    int a,b;
    public void assignValues() {
        a=3;
        b=10;
    }

    public Integer multiply(){
        System.out.println("--multiply called---");
        int res = a*b;
        System.out.println("values :: " + a+ "*" + b +"= " + res);
        return res;
    }
     public Integer multiply(int a, int b){
        int res = a*b;
        System.out.println(a+ "*" + b +"= " + res);
        return res;
    }
}

下面的方面类:

@Component
@Aspect
public class TimeLoggingAspect {
    @Around("execution(* com.test.service.*.*(..))")
    public void userAdvice(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("@Around: Before calculation-"+ new Date());
        joinPoint.proceed();
        System.out.println("@Around: After calculation-"+ new Date());
    } 


     @Before("execution(* com.test.service.assignValues(..))")          
        public void logBeforeV1(JoinPoint joinPoint)
        {
            System.out.println("-before- : " + joinPoint.getSignature().getName());
        } 
}

测试类:

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringAOPTest {
   public static void main(String[] args) {
       //...
       MathService mathService = ctx.getBean(MathService.class);
      mathService.multiply();//i want to call assignValues() method to assign the values of a and b through AOP, before method multiply() is called 
   }
}

每当调用multiple()时,如何使用方面 @Before 调用assignValues()方法。

0 个答案:

没有答案