Spring AOP濡備綍瀹炵幇鏃ュ織璁板綍
Spring AOP 鍙互閫氳繃鍒囬潰鏉ュ疄鐜版棩蹇楄褰曘€傚湪 Spring AOP 涓紝鍙互瀹氫箟涓€涓垏闈紙Aspect锛夛紝骞跺湪璇ュ垏闈腑瀹氫箟閫氱煡锛圓dvice锛夛紝鍦ㄩ€氱煡涓紪鍐欐棩蹇楄褰曠殑閫昏緫銆?/p>
浠ヤ笅鏄竴涓畝鍗曠殑绀轰緥锛?/p>
- 棣栧厛瀹氫箟涓€涓垏闈㈢被锛屼緥濡?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());
}
}
- 鍦ㄩ厤缃枃浠朵腑鍚敤 AspectJ 鑷姩浠g悊锛?/li>
<aop:aspectj-autoproxy/>
- 鍦ㄩ渶瑕佽褰曟棩蹇楃殑鏂规硶涓婃坊鍔犲垏鐐癸紙Pointcut锛夋敞瑙o細
@Service
public class ExampleService {
public void doSomething() {
// Code here
}
}
閫氳繃浠ヤ笂姝ラ锛孲pring AOP 灏卞彲浠ュ疄鐜版棩蹇楄褰曞姛鑳姐€傚湪璋冪敤 ExampleService 绫讳腑鐨勬柟娉曟椂锛孡ogAspect 涓畾涔夌殑閫氱煡鏂规硶浼氳瑙﹀彂锛岃褰曟柟娉曟墽琛屽墠銆佹墽琛屽悗杩斿洖鍊间互鍙婂紓甯镐俊鎭€?/p>