ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring] 스프링 AOP 구현해보기 - AroundAdvice
    프로그래밍 공부/Spring 2021. 5. 5. 14:21

     

    뉴렉처 강사님의 동영상 강의를 정리한 글입니다.

     

     

    Advice

    : 부가 업무 로직을 언제 주 업무 로직에 적용할 지 정의한 것

     

    - Before: 주 업무 로직 실행 전

    - After returnning: 주 업무 실행 후

    - After throwing: 대상 객체의 메서드가 예외를 발생시킨 경우

    - Around: 주 업무 실행 전, 후

     

     

    xml 파일에서 proxy 만들기

     

    Program.java

    ApplicationContext context = new ClassPathXmlApplicationContext("spring/aop/setting.xml");
    		
    Exam exam = new NewlecExam(1,1,1,1);
    Exam proxy = (Exam)context.getBean("proxy");
    System.out.printf("total is %d\n", proxy.total());

     

    setting.xml

    <bean id="target" class="spring.aop.entity.NewlecExam" p:kor="1" p:eng="1" p:com="1" p:math="1"/>
    <bean id="logAroundAdvice" class="spring.aop.advice.LogAroundAdvice"/>
    <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="target"/>
        <property name="interceptorNames">
            <list>
                <value>logAroundAdvice</value>
            </list>
        </property>
    </bean>

     

    java 파일에서 했던 것과 다르게 xml 파일에서 proxy를 생성할 때는 target class와 부가 로직을 실행할  interceptorNames가 필요하다.

     

    target class는 proxy로 만들 대상 클래스. target property를 이용하여 대상 클래스를 넘겨준다.

    위의 코드에서는 bean으로 생성한 NewlecExam 객체를 넘겨주기 때문에 ref로 값을 넘겨줌. (id="target")

     

    interceptorNames에서 부가 로직을 실행하는 클래스들을 넘겨주는데, 복수의 클래스를 받아오는 형태이기 때문에 list 태그를 이용하여 넘겨준다. 

    이때 list는 그룹을 나타내는 추상 변수(?)이므로 안의 값들은 value로 넘겨줘도 추상형태로 들어간다. 

     

    LogAroundAdvice.java

    package spring.aop.advice;
    
    import org.aopalliance.intercept.MethodInterceptor;
    import org.aopalliance.intercept.MethodInvocation;
    
    public class LogAroundAdvice implements MethodInterceptor{
    
    	@Override
    	public Object invoke(MethodInvocation invocation) throws Throwable {
    
    		long start = System.currentTimeMillis();
    		
    		Object result = invocation.proceed();
    		
    		long end = System.currentTimeMillis();
    		String message = (end-start) +"ms 시간이 걸렸습니다.";
    		System.out.println(message);
    		
    		return result;
    	}
    
    }
    

     

    부가 로직을 실행하는 클래스. MethodInterceptor 인터페이스를 구현한 클래스이다.

    target class를 넘겨줄 필요 없다.

     

    '프로그래밍 공부 > Spring' 카테고리의 다른 글

    [Spring] After Returning / Throwing Advice  (0) 2021.05.05
    [Spring] BeforeAdvice 구현하기  (0) 2021.05.05
    [Spring] AOP 코드 구현하기  (0) 2021.05.05
    [Spring] AOP 구현 방식 이해하기  (0) 2021.05.05
    [Spring] AOP란?  (0) 2021.05.05

    댓글

Designed by Tistory.