프로그래밍 공부/Spring

[Spring] AOP 코드 구현하기

valid_ming 2021. 5. 5. 13:14

 

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

 

 

Proxy 이용하여 업무 로직, 부가 로직 분리하기

 

package spring.aop;


import java.lang.reflect.Method;

import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;

import spring.aop.entity.Exam;
import spring.aop.entity.NewlecExam;

public class Program {
	
	public static void main(String[] args) {
		
		Exam exam = new NewlecExam(1,1,1,1);
		
		Exam proxy = (Exam)Proxy.newProxyInstance(NewlecExam.class.getClassLoader(), 
				new Class[] {Exam.class}, 
				new InvocationHandler() {

					@Override
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

						long start = System.currentTimeMillis();
						
						Object result = method.invoke(exam, args);
						
						long end = System.currentTimeMillis();
						String message = (end-start) +"ms 시간이 걸렸습니다.";
						System.out.println(message);
						
						return result;
					}
			
				}
				);
		
		System.out.printf("total is %d\n", proxy.total());
	}
}

 

newProxyInstance

: proxy 객체를 생성하는 메서드 (loader, interfaces, handler)를 파라미터로 갖는다.

 

- loader: 프록시 클래스를 정의하는 클래스 로더 (클래스명.class.getClassLoader())

- interfaces: 프록시 클래스가 구현하는 인터페이스 리스트 (new class[] {인터페이스명1.class, 인터페이스명2.class .. })

- handler: 메서드 호출을 처리하는 핸들러 (new InvocationHandler(){public object invoke(...){...}})