spring " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

spring鍒囬潰鎬庝箞閰嶇疆娉ㄨВ

扬州沐宇科技
2024-02-18 17:24:24
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>

扫码添加客服微信