[Java] Spring AOP @Aspect

minhye kim·2024년 5월 5일

Java

목록 보기
4/11

Spring AOP(Aspect Oriented Programming)는 코드 관심사 분리(Separation of Concerns) 개념을 기반으로 하며, 핵심 비즈니스 로직과 공통적인 관심사(횡단 관심사)를 분리하여 개발 및 유지보수를 용이하게 하는 프로그래밍 패러다임입니다. 핵심 비즈니스 로직은 순수하게 비즈니스 기능에 집중하고, 공통적인 관심사는 AOP 프록시를 통해 별도로 처리합니다.
OOP의 모듈화 핵심 단위는 클래스인 반면, AOP의 모듈화 단위는 측면이다. Aspect를 사용하면 여러 유형과 개체에 걸쳐 문제를 모듈화(예: 트랜잭션 관리, 로그 관리) 할 수 있다.(Crosscutting concerns)

Spring AOP는 AspectJ라는 AOP 프레임워크를 기반으로 하며, AspectJ의 기능을 Spring 프레임워크에 통합하여 개발되었다. 기존 AspectJ는 Java 기반의 프레임워크였지만, Spring AOP는 AspectJ의 기능을 Spring IoC 컨테이너와 연동하여 보다 유연하고 다양한 언어를 지원하도록 개선했다.

AOP 활용

  • 보안: 로그인 인증, 권한 체크, 접근 제어 등
  • 트랜잭션: 데이터베이스 트랜잭션 시작, 커밋, 롤백 등
  • 로그: 메서드 호출 로그, 예외 발생 로그 등
  • 캐싱: 메서드 결과 캐싱
  • 성능 측정: 메서드 실행 시간 측정

Spring AOP의 주요 구성 요소

  • Aspect: 횡단 관심사를 구현하는 코드 모듈
  • Advice: Aspect 내에서 특정 지점에 삽입되는 코드 조각
  • Pointcut: Advice를 적용할 대상 메서드를 지정하는 조건
  • Proxy: Aspect를 적용하여 생성된 대체 객체

예제 코드

@Aspect
public class ConcurrentOperationExecutor implements Ordered {

	private static final int DEFAULT_MAX_RETRIES = 2;

	private int maxRetries = DEFAULT_MAX_RETRIES;
	private int order = 1;

	public void setMaxRetries(int maxRetries) {
		this.maxRetries = maxRetries;
	}

	public int getOrder() {
		return this.order;
	}

	public void setOrder(int order) {
		this.order = order;
	}

	@Around("com.xyz.CommonPointcuts.businessService()") 
	public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
		int numAttempts = 0;
		PessimisticLockingFailureException lockFailureException;
		do {
			numAttempts++;
			try {
				return pjp.proceed();
			}
			catch(PessimisticLockingFailureException ex) {
				lockFailureException = ex;
			}
		} while(numAttempts <= this.maxRetries);
		throw lockFailureException;
	}
}

Reference
https://docs.spring.io/spring-framework/reference/core/aop.html#page-title
https://docs.spring.io/spring-framework/reference/core/aop/ataspectj/example.html
https://velog.io/@orijoon98/Spring-Framework-Documentation3-Aspect-Oriented-Programming

profile
안녕하세요. 블로그를 시작하게 되었습니다! 앞으로 유용한 정보와 좋은 내용을 많이 공유할게요:)

0개의 댓글