Java 在调用方法之前使用spring AOP调用用户定义的方法
我正在使用SpringAOP,下面是服务类和方面。 我想在调用multiply()之前调用assignValues()方法Java 在调用方法之前使用spring AOP调用用户定义的方法,java,spring,spring-aop,Java,Spring,Spring Aop,我正在使用SpringAOP,下面是服务类和方面。 我想在调用multiply()之前调用assignValues()方法 package com.test.service; import org.springframework.stereotype.Service; @Service public class MathService { int a,b; public void assignValues() { a=3; b=10;
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
}
}
如何在调用multiply()时使用aspect@Before调用assignValues()方法。听起来您真正想要的是
@PostConstruct
,您真正想要的是使用构造函数注入,并将此初始化移动到构造函数。@chrylis-我不想要构造函数注入。.这里我只是制作了一个示例(可能我可以给出更好的示例),其中包含我想要的简单示例…调用ever multiply()方法时,我想要调用assignValues()正在调用multiply()之前的方法..我无法触摸MathService类或修改该类中的任何内容..输入将非常有用。谢谢。修复切入点如何?您忘记了类名MathService
。因此切入点应该是执行(*com.test.service.MathService.assignValues(..)
。如果这有助于触发您的方面建议,请让我知道,然后我会将评论转换为您可以接受的答案。如果您需要的话,我还将帮助您调用通知中的另一个方法。听起来您真正想要的是@PostConstruct
,而您真正想要的是使用构造函数注入并将此初始化移动到构造函数。@chrylis-我想要的不是构造函数注入。.这里我只是制作了一个示例(也许我本可以给出更好的)用一个简单的例子来说明我想要什么…当调用ever multiply()方法时,我想在multiply()之前调用assignValues()方法正在调用..我无法触摸MathService类或修改该类中的任何内容..输入将非常有用。谢谢。修复切入点如何?您忘记了类名MathService
。因此切入点应该是execution(*com.test.service.MathService.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;
}
}