Spring AOP 주해 사례 및 기본 원리 상세 설명

4244 단어 SpringAOP주해
절단면:Aspect
절단면=삽입점+알림.오래된 spring 버 전에 서 는 xml 로 설정 되 어 있 으 며,현재 클래스 에@Aspect 주석 을 달 고 있 습 니 다.절단면 은 횡 절 논리(알림)를 지정 한 연결 점 에 짜 는 것 을 책임 집 니 다.
대상:대상
강 화 될 대상.
연결 점:JoinPoint
차단 할 수 있 는 프로그램 실행 점 은 spring 에서 클래스 의 방법 입 니 다.
착안점:PointCut
차단 방법 이 필요 하 다.즉,횡단 논 리 를 구체 적 으로 실시 한 방법 이다.접점 의 규칙 은 spring 에서 AspectJ pointcut expression languge 를 통 해 설명 합 니 다.
접점 과 연결 점 의 차이 점:연결 점 은 모든'자 를 수 있 는 점'입 니 다.착안점 은 진정 으로 잘라 야 할 점 이다.
알림:조언
절 입 점 의 횡 절 논리 에 대해'around','before','after'등 서로 다른 유형의 알림 을 포함 합 니 다.
알림 의 역할 점 이름:
  • before:접점 에 들 어가 기 전에 실행
  • after:접점 에 들 어간 후에 실행
  • around:접점 차단 방법,사용자 정의 전후,더욱 유연
  • 또 일부 이상 처리 통지 가 있 는데,여기 서 일일이 예 를 들 지 않 는 다.
    뜨개질:Weaving
    절단면 과 대상 을 연결 하여 프 록 시 대상 을 만 드 는 과정.spring 에서 사용 하 는 것 은 동적 에이전트 입 니 다.대상 에 게 인터페이스 가 있 으 면 jdk 동적 대 리 를 사용 합 니 다.그렇지 않 으 면 cglib 동적 대 리 를 사용 합 니 다.
    이렇게 많은 개념 을 말 했 는데 코드 의 실현 을 보면 독자 들 이 더욱 깊이 이해 할 수 있 습 니 다.여기 서 주 해 를 통 해 강화 하 는 방법 을 간단하게 쓰 는 AOP-DEmo 입 니 다.
    우선 절단면 류:
    
    package com.example.demo.aop;
    
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.*;
    import org.springframework.stereotype.Component;
    
    /**
     * @author Fcb
     * @date 2020/6/20
     * @description    =   +  
     */
    @Aspect
    @Component
    public class LogAspect {
    
      //          
      @Pointcut("@annotation(com.example.demo.aop.anno.MyLog)")
      public void pointCut() {}
    
      //            
      @After("pointCut()")
      public void recordRequestParam(JoinPoint joinPoint) {
        for (Object s : joinPoint.getArgs()) {
          //      ,          
          System.out.println("after advice : " + s);
        }
      }
    
      //            
      @Before("pointCut()")
      public void startRecord(JoinPoint joinPoint) {
        for (Object s : joinPoint.getArgs()) {
          //      
          System.out.println("before advice : " + s);
        }
      }
    
      //            
      @Around("pointCut()")
      public Object aroundRecord(ProceedingJoinPoint pjp) throws Throwable {
        for (Object s : pjp.getArgs()) {
          //      
          System.out.println("around advice : " + s);
        }
        return pjp.proceed();
      }
    }
    주석:
    
    package com.example.demo.aop.anno;
    import java.lang.annotation.*;
    /**
     * @author Fcb
     * @date 2020/6/20
     * @description
     */
    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD, ElementType.TYPE})
    public @interface MyLog {
    }
    대상 클래스:
    
    package com.example.demo.aop.target;
    
    import com.example.demo.aop.anno.MyLog;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @author Fcb
     * @date 2020/6/20
     * @description
     */
    @RestController
    public class MockController {
    
      @RequestMapping("/hello")
      @MyLog
      public String helloAop(@RequestParam String key) {
        System.out.println("do something...");
        return "hello world";
      }
    
    }
    마지막 으로 테스트 클래스:
    
    package com.example.demo.aop.target;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    /**
     * @author Fcb
     * @date 2020/6/20
     * @description
     */
    @SpringBootTest
    class MockControllerTest {
      @Autowired
      MockController mockController;
    
      @Test
      void helloAop() {
        mockController.helloAop("aop");
      }
    }
    콘 솔 결과:
    around advice : aop
    before advice : aop
    do something...
    after advice : aop
    이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

    좋은 웹페이지 즐겨찾기