CS

[Spring] Spring AOP(Aspect-Oriented Programming)

KJihun 2023. 7. 11. 15:15
728x90

Spring AOP는 관점 지향 프로그래밍이라고도 불리며,

애플리케이션의 핵심 비즈니스 로직과는 별개로 동작해야 하는 동작을 모듈화하고 분리할 수 있도록 도와준다.

@Aspect을 SpringAOP로 설정하려는 class에 작성한다. 

 

 


 

사용목적

1. 로깅(logging): 메서드 실행 시간, 매개변수 값, 리턴 값 등을 기록할 수 있다
2. 보안(security): 인증, 권한 부여 등의 보안 관련 작업을 수행할 수 있다
3. 트랜잭션(transaction): 데이터베이스 트랜잭션 관련 작업을 처리할 수 있다
4. 캐싱(caching): 메서드의 결과를 캐시 하여 성능을 향상할 수 있다.
5. 예외 처리(exception handling): 예외 발생 시 특정 작업을 수행 및 예외를 변환할 수 있다.

 

 


 

구성요소

1. 핵심기능: 수행 될 비즈니스 로직

2. 부가기능: 핵심기능이 언제, 어디서 수행되어야 할지를 설정. 어드바이스와 포인트컷으로 구성된다.

  • 어드바이스: 언제 수행되어야 할지, exception이 발생해도 실행할 건지를 설정
  • 포인트컷: 부가기능이 어디에 수행되어야 할지를 설정

 


 

어드바이스의 종류

@Around: '핵심기능' 수행 전과 후 (@Before + @After)
@Before: '핵심기능' 호출 전 (ex. Client 의 입력값 Validation 수행)
@After:  '핵심기능' 수행 성공/실패 여부와 상관없이 언제나 동작 (ex : try, catch 의 finally())
@AfterReturning: '핵심기능' 호출 성공 시 (함수의 Return 값 사용 가능)
@AfterThrowing: '핵심기능' 호출 실패 시(예외 발생 시): ex. 예외가 발생했을 때 개발자에게 email이나 SMS 보냄)

 

 


 

포인트컷

// ? 는 생략 가능
execution(modifiers-pattern? 
	return-type-pattern
    declaring-type-pattern?
    method-name-pattern(param-pattern) 
    throws-pattern?)

 

포인트컷 Expression 예제

@Around(
"execution(public 
	* 
    com.sparta.myselectshop.controller..
    *(..))"
)
public Object execute(ProceedingJoinPoint joinPoint) throws Throwable { ... }
  • modifiers-pattern
    • public, private, *
  • return-type-pattern
    • void, String, List<String>, *
  • declaring-type-pattern
    • 클래스명 (패키지명 필요)
    • com.sparta.myselectshop.controller.* - controller 패키지의 모든 클래스에 적용
    • com.sparta.myselectshop.controller.. - controller 패키지 및 하위 패키지의 모든 클래스에 적용
  • method-name-pattern(param-pattern)
    • 함수명
      • addFolders : addFolders() 함수에만 적용
      • add* : add 로 시작하는 모든 함수에 적용
    • 파라미터 패턴 (param-pattern)
      • (com.sparta.myselectshop.dto.FolderRequestDto) - FolderRequestDto 인수 (arguments)만 적용
      • () - 인수 없음
      • (*) - 인수 1개 (타입 상관없음)
      • (..) - 인수 0~N개 (타입 상관없음)

 

 

- @Pointcut
    - 포인트컷 재사용 가능
    - 포인트컷 결합 (combine) 가능

    @Component
    @Aspect
    public class Aspect {
         @Pointcut("execution(* com.sparta.myselectshop.controller.*.*(..))")
         private void forAllController() {}
        
         @Pointcut("execution(String com.sparta.myselectshop.controller.*.*())")
         private void forAllViewController() {}
        
         @Around("forAllContorller() && !forAllViewController()")
         public void saveRestApiLog() {
         ...
         }
        
         @Around("forAllContorller()")
         public void saveAllApiLog() {
         ...
     }
}

 

 

AOP 사용 전

 

AOP 사용 후

 

  • Spring이 프록시(가짜 혹은 대리) 객체를 중간에 삽입(DispatcherServlet과 ProductController 입장에서는 변화 X)
    • 호출되는 함수의 input, output 이 완전 동일하다.
    • "joinPoint.proceed()"에 의해서 원래 호출하려고 했던 함수, 인수(argument)가 전달된다.
    • → createProduct(requestDto);

 

 

 

 

[Java] Spring Boot AOP(Aspect-Oriented Programming) 이해하고 설정하기

해당 글에서는 Spring AOP에 대해 이해하고 환경설정을 해보는 방법에 대해서 공유를 목적으로 작성한 글입니다. 1) Spring AOP(Aspect-Oriented Programming, AOP) 1. AOP 용어 이해하기 💡 Spring AOP란? - Spring AOP

adjh54.tistory.com

 

 

Spring - AOP 총정리

Spring의 핵심 개념 중 하나인 DI가 애플리케이션 모듈들 간의 결합도를 낮춘다면, AOP(Aspect-Oriented Programming)는 핵심 로직과 부가 기능을 분리하여 애플리케이션 전체에 걸쳐 사용되는 부가 기능을

velog.io

 

 

OOP (객체지향), AOP(관점지향)

OOP(Object Oriented Programming, 객체지향 프로그래밍) : 모든 데이터를 현실에 빗대어 객체로 다루는 프로그래밍 기법. 객체지향 언어의 5가지 특징은 다음과 같다. 1 ) 캡슐화 (Encapsulation) : 데이터와 함

greendreamtrre.tistory.com

 

'CS' 카테고리의 다른 글

[CS] 스케줄링  (0) 2023.07.15
[CS] 병행(Concurrency)과 병렬(Parallel)  (0) 2023.07.12
[CS] DBMS  (0) 2023.07.08
[Network] HTTP/HTTPS의 차이, SSL/TLS이란?  (1) 2023.07.05
[Spring] IoC, SpringContainer, DI  (0) 2023.06.28