ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [AOP] before의 우선순위
    개발/Spring 2023. 4. 30. 12:59

    옛날에 타일 라이브러리를 이용해서 경로를 각 url에 리소스 위치를 맵핑해줄 때

    상세 경로를 먼저 작성해줘야 url에 따른 파일 위치가 의도대로 맵핑이 됐었다.

    스프링뿐만 아니라 경로 설정 관련해서는 넓은 범위일수록 후미에 배치해야 하는 경우가 많다.

    맥에서 호스트 변조할 때도 마찬가지였다.

    스프링 aop도 같은 맥락으로 동작하는 것 같다.

    다음과 같은 코드가 있다.

    요청이 있을 때 호출되는 메서드의 이름, 인수 타입과 값을 출력해준다.

    @Before("cut()")
        public void before(JoinPoint joinPoint) {
        	System.out.println("ParameterAop Before");
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            System.out.println("method name: " + method.getName());
    
            Object[] args = joinPoint.getArgs();
            for (Object arg : args) {
                System.out.println("type: " + arg.getClass().getSimpleName());
                System.out.println("value: " + arg);
            }
        }

    그리고 Before 동작이 하나 더 있다.

    put 요청을 할 때 이메일을 base64로 인코딩해서 보내면

    서버에서 받아 디코딩한 값을 user 객체에 넣어주는 역할을 한다.

    커스텀 어노테이션을 이용해 상세 조건을 넣어준 메소드다.

    @Before("cut() && enableDecode()")
        public void before(JoinPoint joinPoint) throws UnsupportedEncodingException {
        	System.out.println("DecodeAop Before");
            Object[] args = joinPoint.getArgs();
    
            for (Object arg: args) {
                if (arg instanceof User) {
                    User user = User.class.cast(arg);
                    String base64Email = user.getEmail();
                    String decodedEmail = new String(Base64.getDecoder().decode(base64Email), "UTF-8");
                    user.setEmail(decodedEmail);
                }
            }
        }

    출력은 다음과 같이 나온다.

    DecodeAop Before
    ParameterAop Before
    method name: put
    type: User
    value: User{id=null, pw='null', email='theo@gmail.com'}

    조건이 더 많았던 DecodeAop Before가 먼저 실행되므로

    ParameterAop의 Before에서 확인하는 value에 디코딩된 값인 theo@gmail.com이 뜰 수 있다.

    댓글

Designed by Tistory.