spring core proxy : invocation handler

This commit is contained in:
haerong22
2021-11-16 01:59:17 +09:00
parent beb13babc9
commit 8aa60ae09c
6 changed files with 97 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
package com.example.proxy.jdkdynamic;
import com.example.proxy.jdkdynamic.code.*;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Proxy;
@Slf4j
public class JdkDynamicProxyTest {
@Test
void dynamicA() {
AInterface target = new AImpl();
TimeInvocationHandler handler = new TimeInvocationHandler(target);
AInterface proxy = (AInterface) Proxy.newProxyInstance(AInterface.class.getClassLoader(), new Class[]{AInterface.class}, handler);
proxy.call();
log.info("targetClass={}", target.getClass());
log.info("proxyClass={}", proxy.getClass());
}
@Test
void dynamicB() {
BInterface target = new BImpl();
TimeInvocationHandler handler = new TimeInvocationHandler(target);
BInterface proxy = (BInterface) Proxy.newProxyInstance(BInterface.class.getClassLoader(), new Class[]{BInterface.class}, handler);
proxy.call();
log.info("targetClass={}", target.getClass());
log.info("proxyClass={}", proxy.getClass());
}
}

View File

@@ -0,0 +1,12 @@
package com.example.proxy.jdkdynamic.code;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class AImpl implements AInterface {
@Override
public String call() {
log.info("A 호출");
return "A";
}
}

View File

@@ -0,0 +1,5 @@
package com.example.proxy.jdkdynamic.code;
public interface AInterface {
String call();
}

View File

@@ -0,0 +1,12 @@
package com.example.proxy.jdkdynamic.code;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class BImpl implements BInterface {
@Override
public String call() {
log.info("B 호출");
return "B";
}
}

View File

@@ -0,0 +1,5 @@
package com.example.proxy.jdkdynamic.code;
public interface BInterface {
String call();
}

View File

@@ -0,0 +1,30 @@
package com.example.proxy.jdkdynamic.code;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
@Slf4j
public class TimeInvocationHandler implements InvocationHandler {
private final Object target;
public TimeInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log.info("TimeProxy 실행");
long startTime = System.currentTimeMillis();
Object result = method.invoke(target, args);
long endTime = System.currentTimeMillis();
long resultTime = endTime - startTime;
log.info("TimeProxy 종료 resultTime={}", resultTime);
return result;
}
}