我如何在方法声明中使用@ AOP注释?实际上在java类中有很多重复的代码,所以我在考虑优化it.Only,@around执行值每次都会改变,方法定义对于3-4个methods.Can是相同的,你能建议我在这种情况下做什么来优化代码吗?在给定的例子中,你可以看到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();
}发布于 2019-05-29 04:43:10
AOP意味着你想截取一些逻辑。当使用@around时,你已经准备好将一些逻辑放在你的一些方法之前和之后。这是删除重复代码的好方法。
你需要做的是:
1)查找所有重复代码的方法。
2)将那些重复的代码抽象成一些方法。
3)使用正确的切入点进行配置。
here有更多的例子。希望能帮上忙。
发布于 2019-05-29 12:18:01
你的问题有点不清楚。我猜对了吗?您有多个具有相同方法体的
@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();
}
}如果帮助器方法还需要访问String relationId,只需向其添加另一个参数并相应地调用它。
https://stackoverflow.com/questions/56349734
复制相似问题