1 분 소요

AOP(Aspect Oriented Programming) 자바로 구현하기

1.예전 방법으로 해보기

  • program
public static void main(String[] args) {

		Exam exam = new NewlecExam(1, 1, 1, 1);
		//다른 업무를 가지고 있는 프록시(가짜)
        	}
		
		System.out.printf("total is %d\n", exam.total());

	}
		

public int total() {

		long start = System.currentTimeMillis();
		int result = kor + eng + math + com;
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		long end = System.currentTimeMillis();
		String massage = (end - start) + "ms 시간 걸렸습니다";
		System.out.println(massage);
		return result;

	}


200ms 시간 걸렸습니다
total is 4

 

2.프락시 사용해보기

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);
//				// 모든 형태의 값을 반환 할수 있게 오브젝트 형으로 invoke를 반환

						long end = System.currentTimeMillis();

						String massage = (end - start) + "ms 시간 걸렸습니다";

						System.out.println(massage);

						return result;

					}

				});



		System.out.printf("total is %d\n", exam.total());

	}
}
200ms 시간 걸렸습니다
total is 4

 

-프록시를 이용해서 avg도 끼워 넣을 수 있다

	System.out.printf("total is %d\n", proxy.total());
		System.out.printf("avg is %f\n", proxy.avg());
202ms 시간 걸렸습니다
total is 4
201ms 시간 걸렸습니다
avg is 1.000000

카테고리:

업데이트:

댓글남기기