1. Advisor
- "어떤 시점에 어떤 부가기능을 실행할지"를 정의 (Advice + Pointcut을 묶은 객체)
- Aspect의 최소 단위
2. 구현체
DefaultPointcutAdvisor
Advisor advisor = new DefaultPointcutAdvisor(pointcut, advice);
- 기본 구현체
- Advice + Pointcut를 한 번에 묶어서 등록이 가능
3. Advice 혼합 사용
- 다양한 타입들의 Advice 객체를 혼합해서 하나의 프록시에 등록할 수 있음
예제) ProxyFactory
더보기
더보기
더보기
MyService target = new MyServiceImpl();
ProxyFactory factory = new ProxyFactory();
factory.setTarget(target);
// Advisor 1: BeforeAdvice
factory.addAdvisor(new DefaultPointcutAdvisor(Pointcut.TRUE, new LoggingBeforeAdvice()));
// Advisor 2: AroundAdvice
factory.addAdvisor(new DefaultPointcutAdvisor(Pointcut.TRUE, new TimingAroundAdvice()));
// Advisor 3: ThrowsAdvice
factory.addAdvice(new ExceptionLoggingThrowsAdvice());
MyService proxy = (MyService) factory.getProxy();
4. ProxyFactoryBean
- Spring IoC 컨테이너에서 AOP 프록시를 생성하는 데 사용하는 FactoryBean
속성
속성명 | 설명 |
target |
프록시로 감쌀 실제 타겟 객체
|
proxyInterfaces |
프록시가 구현할 인터페이스 이름 배열
|
interceptorNames |
적용할 어드바이스들의 이름 리스트 (순서 중요)
|
proxyTargetClass |
클래스 기반 프록시 생성
|
optimize |
CGLIB 최적화 사용 여부 (주의해서 사용해야 함)
|
frozen |
설정 후 프록시 수정 허용 여부
|
exposeProxy |
현재 프록시를 ThreadLocal에 노출할지 여부 (AopContext.currentProxy()로 접근 가능)
|
singleton |
매번 같은 객체 반환 여부
|
구현법
상황 | 사용되는 프록시 |
타겟이 인터페이스를 구현함 + proxyTargetClass=false |
JDK 동적 프록시 사용
|
proxyTargetClass=true 설정 |
무조건 CGLIB 프록시 사용
|
인터페이스 없음 |
자동으로 CGLIB 프록시 사용
|
예시)
더보기
더보기
더보기
1. 타겟 객체 등록
@Bean
public PersonImpl personTarget() {
PersonImpl person = new PersonImpl();
person.setName("Tony");
person.setAge(51);
return person;
}
2. 어드바이저 등록
@Bean
public MyAdvisor myAdvisor() {
MyAdvisor advisor = new MyAdvisor();
advisor.setSomeProperty("Custom string property value");
return advisor;
}
@Bean
public DebugInterceptor debugInterceptor() {
return new DebugInterceptor();
}
- Interceptor는 Advice의 인터페이스입니다.
3. ProxyFactoryBean 등록
@Bean
public ProxyFactoryBean personProxyDirect() {
ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
proxyFactoryBean.setTarget(personTarget()); // 실제 객체 (타겟)
proxyFactoryBean.setProxyTargetClass(true); // CGLIB 프록시 사용
proxyFactoryBean.setProxyInterfaces(new Class[]{Person.class}); // 인터페이스도 지정 (혼합 사용 가능)
proxyFactoryBean.setInterceptors(myAdvisor(), debugInterceptor()); // AOP 적용 요소들
return proxyFactoryBean;
}
- setInterceptor에는 Advice, Advisor가 올 수 있음
- Advice 단독으로 올 경우, 전 클래스의 메서드를 대상으로 설정됨
출처
'Spring > Spring' 카테고리의 다른 글
[Spring][AOP] 2. Pointcut API (1) | 2025.04.09 |
---|---|
[Spring][AOP] 1. Advice API (0) | 2025.04.09 |
[Spring][Validation] 2. Java Bean Validation (0) | 2025.04.06 |
[Spring][Validation] 1. Validator Interface (0) | 2025.04.06 |
[Spring][Object] 1. Data Binding (0) | 2025.04.06 |