A>AOP
B> 용어
Aspect: 횡단 관심사(=공통 관심사)
Advice: 횡단 관심사를 구현한 객체
Target: 핵심 로직을 가지고 있는 객체
Proxy: Target 객체 + Advice
joinPoint : Adivce 의 적용대상 == spring 에서는 target 객체의 특정 메서드
PointCut : JoinPoint들 중에서 Adivce가 적용되는 선택의 기준
1.형태
@Advice( pointcut )
C> Adivce의 종류
구분 |
설명 |
Before Advice |
Target의 JoinPoint를 호출하기 전에 실행되는 코드. |
After Returning Advice |
모든 실행이 정상적으로 이루어진 후에 동작하는 코드. |
After Throwing Advice |
예외가 발생한 뒤에 동작하는 코드 |
After Advice |
정상적으로 실행되거나 예외가 발생했을 때 구분 없이 실행되는 코드 |
Around Advice |
메서드의 실행 자체를 제어할 수 있는 가장 강력한 코드. |
D>PointCut
구분 |
설명 |
execution(@execution) |
메서드를 기준으로 Pointcut을 설정. |
within(@within) |
특정한 타입(클래스)을 기준으로 Pointcut을 설정. |
this |
주어진 인터페이스를 구현한 객체를 대상으로 Pointcut을 설정. |
args(@args) |
특정한 파라미터를 가지는 대상들만을 Pointcut으로 설정. |
@annotation |
특정한 어노테이션이 적용된 대상들만을 Pointcut으로 설정. |
1.형태
execution(접근 지정자 클래스 메소드(파라미터) )
2.예시
a>execution(* org.example.service*.*(..))
-- 모든 접근자, service로 시작하는 클래스 의 모든메소드 . 파라미터 뭐든 상관없음
b>execution( * org.example.service.Service*.daAdd(String, String) &&args(s1, s2)
-- doAdd(String s1, String s2) 에 적용한다는 것
c>예외 처리
1
|
@AfterThrowing(pointcut = "execution(* org.zerock.service.SampleService*.*(..))", throwing="exception")
|
cs |
d>ProceedingJoinPoint
ProceedingJoinPoint 는 대상 객체를 호출할 수 있도록 proceed() 메서드를 제공한다.
proceed() 호출하면 after 처럼 사용한다.
1
2
3
4
5
6
7
8
9
11
12
13
14
15
17
18
19
20
21
22
23
24
25
|
@Around("execution(* org.zerock.service.SampleService*.*(..))")
public Object logTime( ProceedingJoinPoint pjp) {
long start = System.currentTimeMillis();
log.info("Target: " + pjp.getTarget());
log.info("Param: " + Arrays.toString(pjp.getArgs()));
Object result = null;
//여기까지는 before 처럼
try {
result = pjp.proceed(); //after로 전환
} catch (Throwable e) {
e.printStackTrace();
}
//after 처럼
long end = System.currentTimeMillis();
log.info("TIME: " + (end - start));
return result;
}
|
cs |
E>spring에서의 사용
1.pom.xml 수정
aspectjrt 와
aspectjweaver 추가
2.root-context.xml 의 수정
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
추가