> For the complete documentation index, see [llms.txt](https://leehyokyun.gitbook.io/openbook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://leehyokyun.gitbook.io/openbook/2-2.-aop.md).

# 2-2. AOP

공통 관심사, AOP에 대하여

### 1. AOP(Aspect Oriented Programming)의 정의와 공통 관심사 분리 메커니즘

* AOP는 관점 지향 프로그래밍을 의미한다.
* 비즈니스 로직의 공통 관심사를 지정하여 이를 별도의 도메인 및 계층으로 분리한다.
* 분리된 공통 로직을 하나의 관점(Aspect)으로 빼서 구성한 뒤, 이를 자동으로 필요한 시점에 끼워 넣는 프로그래밍 방법이다.

### 2. Advice의 정의와 실행 시점 제어

* Advisor는 무엇을(Advice), 어디서(Pointcut),  언제(Rounnd/After/Before) 실행할지에 대한 개념이다.
* 무엇을 관점으로 볼 것인가, 무엇을 공통적인 관심사로 지정할 것인가로 "어떤 행위를 공통적으로 실행할지"에 대한 항목을 명세한다.
* 이 Advice를 "어느 시점"에 적용할 것인지에 대한 정의도 포함하는 개념이다.
* 구체적인 실행 시점 제어 조건으로는 After, Before, Around 등이 존재한다.
* 자바 애노테이션 기반 구체적 예시 구조 : 명세와 같이 특정 연산(어드바이스)이 정상적으로 반환 및 완료된 시점(포인트컷, @AfterReturning)에 핸들러 메서드 로직을 실행하도록 시점을 제어한다.
  * ```
    @AfterReturning(pointcut = "@annotation(CachePut)")
    public void handleCachePut(JoinPoint joinPoint, CachePut cachePut)) 
    ```

### 3. Pointcut의 정의와 JointPoint 필터링 메커니즘

* Pointcut은 어느 위치에, 어느 대상으로 AOP를 적용할 것인지에 대한 대상 및 범위를 의미한다.
* Advice를 "어디에" 적용할 것인지 제어하며, 시간적 시점이 아닌 메서드, 클래스, 패키지 단위로 "위치와 대상"을 지정하는 개념이다.
* Join Point는 메서드 실행 및 생성자 호출 등 AOP를 적용할 수 있는 프로그램 내의 모든 실행 지점을 뜻한다.
* Pointcut은 이 적용 가능한 모든 지점인 Joint Point 중 정확히 어디에 적용할 것인지 필터링한 개념에 해당한다.
* 애플리케이션 환경에서 보통은 메서드 실행 지점을 타깃으로 잡고 필터링을 수행한다.

### 4. Aspect와 AOP의 핵심 차이점

* Aspect는 개별적으로 분리된 핵심 개념들을 하나로 조합한 결과물이다.
* 무엇을 실행할지 정의한 Advice와 어디에 적용할지 필터링한 Pointcut 등의 개념들을 유기적으로 조합하여, 공통 관심사를 하나의 모듈 혹은 체계로 구성해 놓은 구성을 Aspect라 한다.
* AOP는 이러한 Aspect들을 활용하여 공통 관심사를 격리하고 필요한 시점에 자동으로 끼워 넣는 패러다임이자 프로그래밍 방법론 전체를 아우르는 상위 개념이다.

### 5. AOP/Interceptor/Filter

```
Client
  │
  │ HTTP Request
  ▼
┌─────────────────────┐
│      Filter         │  ← Servlet 수준
│  요청/응답 자체      │
└─────────┬───────────┘
          ▼
┌─────────────────────┐
│   DispatcherServlet  │
└─────────┬───────────┘
          ▼
┌─────────────────────┐
│    Interceptor      │  ← Spring MVC 수준
│  Controller 호출 전후│
└─────────┬───────────┘
          ▼
┌─────────────────────┐
│    Controller        │
│      Method          │
└─────────┬───────────┘
          ▼
┌─────────────────────┐
│       AOP            │  ← Spring Bean/Method 수준
│ Service 메서드 등    │
└─────────────────────┘
```

#### AOP&#xD;

* AOP의 핵심은 공통 관심사, Interceptor & Filter와 같이 요청의 중간에 공통적인 로직을 추가한다는 것은 유사하다. 하지만, Servlet(Filter) / MVC Controller 이전(Interceptor)와 달리 서비스 메소드, Repository, Bean 등 서비스 로직에 더욱 직접적으로 사용자 맞춤의 공통 관심사 로직을 구성하고 실행할 수 있다는 점이 가장 큰 차이점.
* AOP는 Spring Application 실행시점에 어떤 포인트컷/advice 등을 통해 언제 무엇을 AOP 적용할지 정의한다. 이때 정의한 지점을 프록시로 Wrapping, 해당 포인트컷 및 Advice 부합 시 프록시를 실행하도록 되어있다.

#### Filter

* Filter의 경우 Servlet Container의 매우 앞단(HTTP Req/Res) 수준에서 관련 요소들을 다룬다. 따라서, HTTP에서 다룰법한 CORS/HTTP Req\&Res 로깅/global 요청에 대한 처리 등이라면 가장 먼저 고려해야 한다.

#### Interceptor

* &#x20;Interceptor의 경우 Servlet 측에서 MVC Controller를 호출 전/후(pre/postHandler) 개입한다. 특정 URL(엔드포인트)에 적용할 수도 있으며, 특정 도메인(Controller)의 요청에 공통 로직을 적용할때 사용한다.

\
\ <br>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://leehyokyun.gitbook.io/openbook/2-2.-aop.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
