[英]How can I use @around spring aop annotation on method declaration?
如何在方法声明中使用@around spring AOP注释? 实际上java类中有很多重复的代码,所以我想优化它。只有@around执行值每次都会改变,3-4方法的方法定义相同。你能建议我能做什么这种情况下的代码优化?在给定的例子中你可以看到nicdStatus和nicdPortStatus只是被改变了,所有的方法定义都是相同的。 请提供代码优化的一些建议,因为我的java类中有重复的代码。
@Around("execution(* dcp.casa.services.nicd.NicdController.**nicdStatus**(..)) && args(*, relationId,..)")
Object handleRunTest(final ProceedingJoinPoint joinPoint, final String relationId) {
log.info("xyz");
callAbc();
return joinPoint.proceed();
}
@Around("execution(* dcp.casa.services.nicd.NicdController.nicdPortStatus(..)) && args(*, relationId,..)")
Object handleRunTest(final ProceedingJoinPoint joinPoint, final String relationId) {
log.info("xyz");
callAbc();
return joinPoint.proceed();
}
AOP意味着你想拦截一些逻辑。 使用@around时,您已准备好在某些方法之前和之后放置一些逻辑。 这是删除重复代码的好方法。
你需要做什么:
1)找到具有重复代码的所有方法。
2)将这些重复代码抽象为一些方法。
3)使用正确的切入点配置。
这里有更多的例子。 希望可以帮助。
你的问题有点不清楚。 我是否正确地猜测你有多个具有相同方法体的
@Around
建议方法,并且你想将这些方法体分解为一个辅助方法,以避免你方面的代码重复?是的,你是对的@kriegaex。 你了解我的问题。
嗯,那么答案很简单:重构就像重构任何其他Java类一样:
package de.scrum_master.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Aspect
public class LoggingAspect {
private static final Logger log = LoggerFactory.getLogger(LoggingAspect.class);
private void callAbc() {}
@Around("execution(* dcp.casa.services.nicd.NicdController.**nicdStatus**(..)) && args(*, relationId, ..)")
public Object handleRunTestA(ProceedingJoinPoint joinPoint, String relationId) throws Throwable {
return handleRunHelper(joinPoint);
}
@Around("execution(* dcp.casa.services.nicd.NicdController.nicdPortStatus(..)) && args(*, relationId, ..)")
public Object handleRunTestB(ProceedingJoinPoint joinPoint, String relationId) throws Throwable {
return handleRunHelper(joinPoint);
}
private Object handleRunHelper(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("xyz");
callAbc();
return joinPoint.proceed();
}
}
如果helper方法也需要访问String relationId
,只需添加另一个参数并相应地调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.