Back-End/Spring
[Spring] AOP (Aspect Oriented Programming)
zsunny
2023. 4. 28. 15:08
AOP 등장 배경
기존 OOP에서 핵심 관심 사항(core concern)과 공통 관심 사항(cross-cutting concern)을 여러 모듈에 중복 사용되는 한계를 해결하기 위해 AOP가 등장했다. 공통 관심 사항을 기준으로 프로그래밍함으로써 공통 모듈을 손쉽게 적용할 수 있게 한다.
AOP 특징
- AOP는 핵심적인 기능에서 부가적인 기능을 분리
- Aspect 라는 모듈 형태로 만들어 설계하고 개발해 객체지향적인 가치를 지킬 수 있게하는 개념
AOP 용어
- Target : 핵심기능을 담고 있는 모듈. 부가기능의 부여 대상
- Advice : 어느 시점에 공통 관심 기능 Aspect을 적용할지 정의. Target에 제공할 부가기능 담음
- JoinPoint : Aspect가 적용될 수 있는 지점. target 객체가 구현한 인터페이스의 모든 method
- Pointcut : 공통 관심 사항이 적용될 JoinPoint. Advice를 적용할 target의 method를 선별하는 정규 표현식(execution으로 시작)
- Aspect : Advice + Pointcut (Singleton 형태의 객체로 존재)
- Weaving : 어떤 Advice를 어떤 Pointcut에 적용시킬 것인지에 대한 설정
Spring의 AOP 구현
< POJO (.xml) 버전 >
public void aop_before(JointPoint jp){
String name = joinPoint.getSignature().toShortString();
System.out.println("Advice : " + name);
}
<aop:config>
<aop:aspect id="beforeAspect" ref="">
<aop:pointcut id=="aop_before" expression="execution(public * com.test..." />
<aop:before method="before" pointcut-ref="" />
</aop:aspect>
</aop:config>
< Annotation 버전 >
설정 파일에 aop:aspectj-autoproxy/ 추가go Aspect Class를 으로 등록한다.
- @Aspect : Aspect Class 선언
- @Before("pointcut")
- @AfterReturning(pointcut="", returning="")
- @AfterThrowing(pointcut="", throwing="")
- @After("pointcut")
- @Around("pointcut")
public class Aspect {
@Pointcut("execution(public * com.test...)")
public void aop_target(){}
@Around("aop_target()")
public Object aop_around(ProceedingJoinPoint joinPoint) {
...
}
}