Spring

AOP

Hasky96 2022. 9. 4. 23:31

AOP(Aspect Oriented Programming)

  • 언제 필요할까?
    • 공통적인 로직(공통 관심 사항) 을 수정하거나 추가할 때!
    • ex) 서비스 로직 전부에 공통된 기능을 추가할 때
  • AOP 적용
    • 공통 관심 사항(cross-cutting concern) vs 핵심 관심 사항(core concern) 분리
    • 공통 관심 사항을 필요한 곳에 적용
    • @Aspect annotation을 활용하여 사용
//EXAMPLE

@Aspect
//@Component => 보통 config에 정의 하여 사용
public class TestAop{
	
    //코드의 수행시간 확인 코드
    @Around("execution(* hello.hellospring..*(..))") //hello.hellospring 내부 모두 적용
    //@Around("execution(* hello.hellospring.service..*(..))") //hello.hellospring.service 내부 모두 적용
    public Object(ProceedingJoinPoint joinpoint) throw Throwable{
    	
        long start = System.currentTimeMillis();
        System.out.println("START : "+ joinPoint.toString());
        
        try{
        	Object result = joinPoint.proceed();
        } finally{
        	long finish = System.currentTimeMillis();
            long timeMs = finish - start;
            System.out.println("END : "+ joinPoint.toString()+" "+ timeMs + "ms");
        }
    }
}

//config
/** 생략*/

@Bean
public TestAop testAop(){
	return new TestAop();
}

/** 생략*/

 

* 핵심사항과 공통사항을 구분하고 공통사항을 분리하여 사용한다.

 

  • 장점
    • 핵심 관심 사항을 깔끔하게 유지할 수 있다.
    • 변경이 필요하면 공통 관심 사항만 수정하면 된다.
    • 원하는 적용 대상을 선택할 수 있다.
  • 어떻게 되는 거지?
    • AOP를 적용하면 프록시(스프링이 복제하여 만든 가짜 스프링 빈)를 호출하고 이후에 ```joinPoint.proceed()```가 실제를 호출함