springaop " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

Spring AOP濡備綍瀹炵幇鏃ュ織璁板綍

扬州沐宇科技
2024-06-19 16:41:13
springaop

Spring AOP 鍙互閫氳繃鍒囬潰鏉ュ疄鐜版棩蹇楄褰曘€傚湪 Spring AOP 涓紝鍙互瀹氫箟涓€涓垏闈紙Aspect锛夛紝骞跺湪璇ュ垏闈腑瀹氫箟閫氱煡锛圓dvice锛夛紝鍦ㄩ€氱煡涓紪鍐欐棩蹇楄褰曠殑閫昏緫銆?/p>

浠ヤ笅鏄竴涓畝鍗曠殑绀轰緥锛?/p>

  1. 棣栧厛瀹氫箟涓€涓垏闈㈢被锛屼緥濡?LogAspect锛?/li>
@Aspect
@Component
public class LogAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {
        logger.info("Method executed: " + joinPoint.getSignature());
    }

    @AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result")
    public void logAfterReturning(JoinPoint joinPoint, Object result) {
        logger.info("Method returned: " + result);
    }

    @AfterThrowing(pointcut = "execution(* com.example.service.*.*(..))", throwing = "exception")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable exception) {
        logger.error("Method threw exception: " + exception.getMessage());
    }

}
  1. 鍦ㄩ厤缃枃浠朵腑鍚敤 AspectJ 鑷姩浠g悊锛?/li>
<aop:aspectj-autoproxy/>
  1. 鍦ㄩ渶瑕佽褰曟棩蹇楃殑鏂规硶涓婃坊鍔犲垏鐐癸紙Pointcut锛夋敞瑙o細
@Service
public class ExampleService {

    public void doSomething() {
        // Code here
    }

}

閫氳繃浠ヤ笂姝ラ锛孲pring AOP 灏卞彲浠ュ疄鐜版棩蹇楄褰曞姛鑳姐€傚湪璋冪敤 ExampleService 绫讳腑鐨勬柟娉曟椂锛孡ogAspect 涓畾涔夌殑閫氱煡鏂规硶浼氳瑙﹀彂锛岃褰曟柟娉曟墽琛屽墠銆佹墽琛屽悗杩斿洖鍊间互鍙婂紓甯镐俊鎭€?/p>

扫码添加客服微信