package com.spring.jdkTest;
public interface Iuser {
void printOne();
void printTwo();
}
package com.spring.jdkTest;
public class UserImpl implements Iuser {
@Override
public void printOne() {
System.out.println("One");
}
@Override
public void printTwo() {
System.out.println("Two");
}
}
package com.spring.advice;
public class Advice {
public void before() {
System.out.println("前");
}
public void after() {
System.out.println("后");
}
}
package com.spring.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.spring.advice.Advice;
import com.spring.jdkTest.Iuser;
import com.spring.jdkTest.UserImpl;
public class MyProxy {
public static Iuser getIuser() {
Iuser user = new UserImpl();
Advice advice = new Advice();
Iuser userProxy = (Iuser)Proxy.newProxyInstance(MyProxy.class.getClassLoader(),
user.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
advice.before();
Object obj =method.invoke(user, args);
advice.after();
return obj;
}
});
return userProxy;
}
}
package com.spring.jdkTest;
import org.junit.Test;
import com.spring.proxy.MyProxy;
public class SpringTest {
@Test
public void test() {
Iuser user = MyProxy.getIuser();
user.printOne();
user.printTwo();
}
}
前
One
后
前
Two
后