[Spring/Springboot] AOP 관점 지향 프로그래밍
2024. 12. 15. 23:06ㆍCS/Spring
AOP(aspect-oriented programming) : 관점 지향 프로그래밍
- AOP는 핵심 비즈니스 로직에 직접적인 변경 없이, 추가적인 작업(횡단 관심사)을 더 쉽게 관리할 수 있게 해줌
- 횡단 관심사(cross-cutting concern)의 분리를 허용함으로써 모듈성을 증가시키는 것이 목적인 프로그래밍 패러다임
- 코드 그 자체를 수정하지 않는 대신 기존의 코드에 추가 동작(어드바이스)을 추가함으로써 수행
- 어느 코드가 포인트컷(pointcut) 사양을 통해 수정되는지를 따로 지정
- 기능의 코드 핵심부를 어수선하게 채우지 않고도 비즈니스 로직에 핵심적이지 않은 동작들을 프로그램에 추가할 수 있게 함
AOP 예시 시나리오
- 여러분이 친구들을 초대해서 집에서 '스파게티 파티'를 열기로 했다고 상상해보세요. 스파게티를 만드는 것이 핵심 요리 과정이고, 요리 중에는 여러 가지 부수적인 작업이 필요합니다. 예를 들어, 요리를 시작하기 전 손 씻기, 재료 준비, 설거지 같은 일들 말이죠. 이 부수적인 일들은 요리와는 직접 관련이 없지만, 파티의 성공을 위해 필수적 ⇒ 부수적인 일들을 AOP로 처리
- 핵심 비즈니스 로직 (스파게티 만들기)
// 스파게티 요리 클래스
public class SpaghettiChef {
public void makeSpaghetti() {
System.out.println("스파게티를 만들고 있습니다.");
}
}
- AOP Aspect 클래스 (부수적인 작업 처리)
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class CookingAspect {
// 요리 시작 전 해야 할 일 (Before 어노테이션 사용)
@Before("execution(* SpaghettiChef.makeSpaghetti(..))")
public void washHands() {
System.out.println("요리 전에 손을 씻습니다.");
}
// 요리가 끝난 후 해야 할 일 (After 어노테이션 사용)
@After("execution(* SpaghettiChef.makeSpaghetti(..))")
public void cleanUp() {
System.out.println("요리가 끝난 후 부엌을 청소합니다.");
}
}
- Spring 설정 정보
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan(basePackages = "com.example") // 패키지 스캔
@EnableAspectJAutoProxy // AOP 활성화
public class AppConfig {
}
- Main 클래스 (스파게티 파티 실행)
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
// Spring 컨텍스트 초기화
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
// 스파게티 요리사 빈 가져오기
SpaghettiChef chef = context.getBean(SpaghettiChef.class);
// 스파게티 요리 시작
chef.makeSpaghetti();
}
}
- 실행 결과
요리 전에 손을 씻습니다.
스파게티를 만들고 있습니다.
요리가 끝난 후 부엌을 청소합니다.
- 핵심 로직: SpaghettiChef 클래스는 스파게티를 만드는 것이 핵심 로직
- 횡단 관심사: 손 씻기와 청소 같은 작업은 AOP를 통해 핵심 로직 외부에서 처리
- @Before와 @After 어노테이션을 사용해, 요리를 시작하기 전에 손을 씻고, 요리가 끝난 후 청소하는 로직을 쉽게 추가
- 이처럼, AOP는 핵심 비즈니스 로직에 직접적인 변경 없이, 추가적인 작업(횡단 관심사)을 더 쉽게 관리할 수 있게 해줌
'CS > Spring' 카테고리의 다른 글
[Spring/Springboot] 도메인/양방향매핑/N+1 문제 (0) | 2024.12.15 |
---|---|
[Spring/Springboot] 서블릿(Servlet) (0) | 2024.12.15 |
[Spring/Springboot] API, 프레임워크, 라이브러리의 차이 (0) | 2024.12.15 |
[Spring/Springboot] Bean/싱글톤 패턴/컴포넌트 스캔 (0) | 2024.12.15 |
[Spring/Springboot] 제어의 역전 IoC(Inversion of Control) (0) | 2024.12.15 |