Spring

AOP

kenzi 2022. 4. 4. 16:00

Aspect Oriented Programming 관점지향 프로그래밍 

 

왜 등장?

-"공통 관심사항(기능)과 핵심 관심사항(기능)을 분리해서 보자" 에서 시작

공통 관심사항은 외부에서 주입해주자

 

예를 들어 

로그인 확인하고 안 되어있으면 다른 폼으로 넘겨주는 작업을 매번(글쓰기, 수정, 삭제등) 했는데 

글쓰기 메서드를 처리하기 전에 로그인 기능(공통 관심사항)이 이미 주입되어서 실행된 상태가 된 것 

 

예를 들어 

회사에 출근하는데 건물 내 사무실을 드나들때 매번 사원증 확인하고 들어가야한다면 너무 번거로움

메인 출입구에서만 확인하면 신분확인이 되니까 간편함 

 

그럼으로써?

중복 코드 제거에 따른 코드의 간결성 

생산성 향상 

공통기능이 빠진 클래스는 재사용 가능 

유지보수 향상 

 

 

 

 

어떻게 사용하나?

스프링 공식문서 

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-introduction-defn

 

Core Technologies

In the preceding scenario, using @Autowired works well and provides the desired modularity, but determining exactly where the autowired bean definitions are declared is still somewhat ambiguous. For example, as a developer looking at ServiceConfig, how do

docs.spring.io

5.1. AOP Concepts

AOP의 주요용어

  • Aspect: A modularization of a concern that cuts across multiple classes. Transaction management is a good example of a crosscutting concern in enterprise Java applications. In Spring AOP, aspects are implemented by using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style).
  • Join point: A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.
  • Advice: Action taken by an aspect at a particular join point. Different types of advice include “around”, “before” and “after” advice. (Advice types are discussed later.) Many AOP frameworks, including Spring, model an advice as an interceptor and maintain a chain of interceptors around the join point.
  • Pointcut: A predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut expression language by default.
  • Target object: An object being advised by one or more aspects. Also referred to as the “advised object”. Since Spring AOP is implemented by using runtime proxies, this object is always a proxied object.
  • Weaving: linking aspects with other application types or objects to create an advised object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.

Aspect : 여러 객체 공통으로 적용되는 공통 관심사항을 Aspect라고 칭함 (트랜잭션이나 보안같은 공통 관심사항)

JoinPoint : Advice가 적용 가능한 지점을 의미 (핵심 로직 Service Method를 의미) 

Advice : 언제 공통 관심기능을 핵심로직에 적용할지를 정의한다.

예를 들어 'method'를 호출하기 전에 트랜잭션을 시작한다 등의 기능을 적용한다는 것을 정의하는 것 (시점이 중요하다)

PointCut : Advice가 적용되는 JoinPoint를 정의하는 정규표현식이나 AspectJ의 문법 

Weaving :  Advice를 핵심 로직 코드에 적용하는 것이 Weaving

 

 

 

advice의 종류 

Spring AOP includes the following types of advice:

  • Before advice: Advice that runs before a join point but that does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).
  • After returning advice: Advice to be run after a join point completes normally (for example, if a method returns without throwing an exception).
  • After throwing advice: Advice to be run if a method exits by throwing an exception.
  • After (finally) advice: Advice to be run regardless of the means by which a join point exits (normal or exceptional return).
  • Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

Before Advice - 조인포인트 실행 전 (대상 객체의 메서드 호출 전에) 공통 기능 실행

After Returning Advice - 예외 없이 실행 후 공통 기능 실행

After Throwing Advice - 예외 발생시 공통기능 실행

After Advice - 예외 발생 여부와 상관없이 메서드 실행 후 공통 기능 실행 

Around Advice - before와 after를 한번에 하는 것  

 

적용순서 :

명시적 지정방법 : order이용

 

방식 : xml과 @(annotation)방식이 있다 

xml방식은 

<aop: *>방식으로 태그를 건다 

ex) <aop:config>

      <aop:aspect ~

        

         

@방식은 

@Aspect 어노테이션을 사용한다 

 

ex) @Aspect 

        @Before ...

        @After ... 

 

)


advice는 시점을 정의하는 것이다

joinpoint는 핵심서비스에서 aop 가능한 지점 

pointcut은 advice시점에서 어떤 조건으로 joinpoint를 찾아낼것인지 고르는 것