본문 바로가기

java/spring

Spring AOP ( annotation 활용)

[Class]

@Aspect

 

[Method]

@PointCut

 

표현식 예제 참고 사이트)

https://docs.spring.io/spring-framework/docs/2.5.x/reference/aop.html

 

@Before : 이전
@After : 이후
@AfterReturning : 정상적 반환 이후
@AfterThrowing : 예외 발생 이후
@Around : 메소드 실행 전후

 

어노테이션을 이용한 AOP 적용 예제

package com.example.aop.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface 어노테이션a {
}

 

package com.example.aop.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class 타겟처리클래스 {

    @Pointcut("execution(* com.example.aop.controller..*.*(..))")
    private  void 메서드a(){}

    @Pointcut("@annotation(com.example.aop.annotation.어노테이션a)")
    private  void 메서드b(){}

    @Before("메서드a() && 메서드b()")
    public void before(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();

        ...
    }

    @AfterReturning(value = "메서드a() && 메서드b()", returning = "반환객체변수명a")
    public void afterReturn(JoinPoint joinPoint, Object 반환객체변수명a){

        ...
    }

}
package com.example.aop.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class RestApiController2 {

    @어노테이션a
    @PutMapping("/put")
    public 반환객체b put(@RequestBody 객체a 변수명){

        ...

        return 반환객체b ;
    }
}

 

반응형

'java > spring' 카테고리의 다른 글

Spring Filter  (0) 2022.06.17
Spring Exception  (0) 2022.04.07