spring鍒囬潰鎬庝箞閰嶇疆娉ㄨВ
瑕佸湪Spring涓厤缃垏闈㈡敞瑙o紝棣栧厛闇€瑕佸湪閰嶇疆鏂囦欢涓惎鐢ˋspectJ鑷姩浠g悊銆傚彲浠ラ€氳繃鍦ㄩ厤缃枃浠朵腑娣诲姞浠ヤ笅鍐呭鏉ュ惎鐢ˋspectJ鑷姩浠g悊锛?/p>
<aop:aspectj-autoproxy/>
鐒跺悗锛屽湪鍒囬潰绫讳笂娣诲姞 @Aspect
娉ㄨВ鏉ユ爣璇嗚绫讳负鍒囬潰绫伙紝鍐嶅湪鍒囬潰绫讳腑瀹氫箟鍒囩偣鍜岄€氱煡鏂规硶銆備緥濡傦細
@Aspect
@Component
public class MyAspect {
@Pointcut("execution(* com.example.service.*.*(..))")
public void serviceMethods() {}
@Before("serviceMethods()")
public void beforeServiceMethod(JoinPoint joinPoint) {
System.out.println("Before executing service method: " + joinPoint.getSignature().getName());
}
@AfterReturning(pointcut = "serviceMethods()", returning = "result")
public void afterReturningServiceMethod(JoinPoint joinPoint, Object result) {
System.out.println("After returning from service method: " + joinPoint.getSignature().getName());
}
@AfterThrowing(pointcut = "serviceMethods()", throwing = "exception")
public void afterThrowingFromServiceMethod(JoinPoint joinPoint, Exception exception) {
System.out.println("After throwing from service method: " + joinPoint.getSignature().getName());
}
}
鍦ㄤ笂闈㈢殑渚嬪瓙涓紝@Pointcut
娉ㄨВ瀹氫箟浜嗕竴涓垏鐐癸紝閫氳繃 execution(* com.example.service.*.*(..))
琛ㄨ揪寮忓尮閰嶄簡 com.example.service 鍖呬笅鐨勬墍鏈夋柟娉曘€傜劧鍚庝娇鐢?@Before
銆?code>@AfterReturning銆?code>@AfterThrowing 绛夋敞瑙e畾涔変簡鍚勭閫氱煡鏂规硶銆?/p>
鏈€鍚庯紝纭繚閰嶇疆鏂囦欢涓凡缁忔壂鎻忓埌浜嗗垏闈㈢被鎵€鍦ㄧ殑鍖咃紝杩欐牱Spring瀹瑰櫒灏辫兘澶熻嚜鍔ㄨ瘑鍒苟搴旂敤鍒囬潰娉ㄨВ銆?/p>
相关问答