개발/Spring

SPRING_AOP(Aspect-Oriented Programming) 관점 지향 프로그래밍

Zziny 2021. 10. 12. 02:52

AOP 용어

- Advice : 공통관심사를 모듈화한 객체

- Join Point : 공통관심사를 적용할 수 있는 모든 대상

    *Spring의 Join Points는 Bean으로 등록된 모든 객체의 메서드

- Pointcuts : Join Points 중에서 실제로 Advice를 적용할 대상

- Aspect : Advice + Pointcuts, 공통관심사

- target : Pointcut을 가진 객체

- Weaving : Advice와 target을 결합해 프록시 객체를 생성하는 과정

- Proxy : Weaving의 결과로 만들어진 프록시 객체


STEP1

Proxy 객체를 생성하는 일을 해줄 Bean을 등록, DefaultAdvisorAutoProxyCreator

<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>

STEP2

Advice와 Pointcut을 지정할 Bean을 등록, AspectJExpressionPointcutAdvisor

<bean class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor">
    <!-- Advice로 사용할 클래스를 지정 -->
    <property name="advice" ref="myAdvice" />
    
    <!-- Advice를 적용할 대상, pointcuts을 지정 -->
    <!-- Pointcut Expression
    * : 모든
    .. : 0개 이상
    [접근제한자] 리턴타입 [패키지.클래스].메서드(매개변수) -->
    <property name="expression" value="execution(public * aop01.*.*(..))"/>
</bean>

 

STEP1

Namespaces -> context, aop 추가

STEP2

<aop:aspectj-autoproxy/>

STEP3

공통관심사로 적용할 메서드와 Pointcut 지정 

<aop:config>
    <aop:aspect ref="myAdvice">
        <aop:before method="before" pointcut="execution(* *(..))"/>
        <aop:after method="after" pointcut="execution(* *(..))"/>
        <aop:after-throwing method="afterThrowing" pointcut="execution(* *(..))"/>
    </aop:aspect>
</aop:config>

STEP1

Namespaces -> context, aop 추가

STEP2

<aop:aspectj-autoproxy/>

STEP3

Advice로 사용할 클래스에 @Aspect 추가

@Component
@Aspect
public class MyAdvice {
	//Before : target 클래스의 메서드가 실행 되기 전
	//After : target 클래스의 메서드가 실행 된 이후
	//AfterReturning : target 클래스의 메서드가 문제없이 실행이 된 이후
	//AfterThrowing : target 클래스의 메서드를 실행하다 예외가 발생한 이후
	//Around : target 클래스의 메서드가 시작되기 전과 실행 이후
	
	@Before(value= "execution(* *(..))")
	public void before() {
		System.out.println("출근 카드를 찍는다.");
	}

	@After("execution(* *(..))")
	public void after() {
		System.out.println("집에 도착한다.");
	}
	
	@AfterReturning(value= "execution(* *(..))", returning = "res")
	public void afterReturning(Object res) {
		System.out.println(res);
		System.out.println("집에 간다.");
	}
	
	@AfterThrowing(value= "execution(* *(..))", throwing = "exception")
	public void afterThrowing(Exception exception) {
		System.out.println(exception.getMessage());
		System.out.println("쉬는 날 이었다.");
	}
}