Spring Boot AOP 개념 및 사용법

과녁스·2021년 9월 28일
1

Spring

목록 보기
7/11
post-thumbnail

개요


AOP(Aspect Oriented Programming)는 관점 지향 프로그래밍이다. 어떠한 기준을 정하고, 관점을 나누어서 각 관점 별로 모듈화를 하여 사용하는 방식이다.

AOP를 사용하는 이유는 비즈니스 로직과 공통 기능으로 구분을 하고, 공통 기능은 필요한 시점에 불러와서 적용하는 프로그래밍 방법이다.

관점을 기준으로 로직을 모듈화한다는 것은 코드들을 부분적으로 나누어서 모듈화하겠다는 의미다.

소스 코드상에서 다른 부분에 계속 반복해서 쓰는 코드들을 확인할 수 있는 데 이것을 흩어진 관심사 (Crosscutting Concerns)❓라 부른다.

스프링 MVC 웹 어플리케이션에서는 Web Layer, Business Layer, Data Layer로 정의

  • Web Layer : Rest API를 제공하며, 클라이언트 중심의 로직 적용
  • Businuess Layer : 내부 정책에 따르는 로직을 개발하며, 주로 해당 부분 개발
  • Data Layer : 데이터베이스 및 외부와의 연동 처리

시작하기


라이브러리 추가

dependencies {
    implementation 'org.springframework:spring-aop'
}

@EnableAspectAutoProxy

  • @SpringBootApplication 또는 @Configuration을 사용한 클래스에서 @EnableAspectAutoProxy를 추가하면 Spring AOP를 사용이 가능
@SpringBootApplication
@EnableAspectAutoProxy
public class SampleApplication {
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
    }
}

어노테이션 설명 및 사용법


@Aspect

  • 스프링 빈에 등록된 클래스에서 @Aspect를 추가하면 해당 빈이 Aspect로 작동
  • 클래스에 @Order를 명시하여 @Aspect로 등록된 빈 간의 작동 순서를 정할 수 있음
  • 순서는 int 타입의 정수로 순서를 정할 수 있는데 값이 낮을수록 우선순위가 높음.
  • 순서의 기본값은 가장 낮은 우선순위를 가지는 Ordered.LOWEST_PRECEDENCE
  • @Aspect가 등록된 빈에는 어드바이스(Advice)라 불리는 메써드를 작성 가능
  • 대상 스프링 빈의 method의 시점과 방법에 따라 @Before, @After, @AfterReturning, @AfterThrowing, @Around 등을 명시

@Before

  • @Aspect 클래스의 method 레벨에 @Before 어드바이스를 명시하면 대상 method 실행 전에 원하는 작업을 설정
  • 끼어들기만 할 뿐 대상 메써드의 제어나 가공은 불가능
@Before("execution(* com.example.*.*(..))")
public void somethingBefore(JoinPoint joinPoint) {
}
  • 어드바이스 parameter의 내용은 PointCut이라는 표현식
  • 끼어들 메써드의 범위를 지정
  • 전달 받는 JoinPoint 오브젝트는 method의 정보를 담고 있음

@AfterReturning

  • @AfterReturning을 설정하면 해당 method의 실행이 종료되어 값을 리턴할 때
@AfterReturning(pointcut = "execution(* com.example.*.*(..))", returning = "result")
public void doSomethingAfterReturning(JoinPoint joinPoint, Object result) {
	// 리턴 시 실행
}

@Around

  • @Around 어드바이스는 앞서 설명한 어드바이스의 기능을 모두 포괄
  • 대상 method를 실행 앞/뒤 시점에 원하는 작업 설정 가능
// 특정 어노테이션이 명시된 모든 메써드의 실행 전후로 끼어들 수 있다.
@Around("@annotation(sampleAnnotation)")
public Object somethingAround(final ProceedingJoinPoint joinPoint, final SomeAnnotation someAnnotation) {

    // 실행 전
    Object result = joinPoint.proceed();
    // 실행 후

    return result;
}
// 특정 어노테이션이 설정된 모든 method 실행 앞/뒤
@Around("@annotation(scheduled)")
public Object process(final ProceedingJoinPoint joinPoint, final Scheduled scheduled) throws Throwable {
}

// 클래스 레벨에 특정 어노테이션이 명시된 모든 method
@Around("@within(org.springframework.web.bind.annotation.RestController) || @within(org.springframework.stereotype.Service) || @within(org.springframework.stereotype.Repository)")
public Object process(final ProceedingJoinPoint joinPoint) throws Throwable {
}

JoinPoint 객체

JoinPoint객체는 각 컨트롤러에 정의된 method들의 args(매개변수)정보를 담고 있는 객체이다.

profile
ㅎㅅㅎ

0개의 댓글