AOP原理----动态代理的spring模拟实现(JDK+ InvocationHandler)

public class Main {
	public static void main(String[] args) {
		UserService userService = new UserServiceImpl();
		InvocationHandler invocationHandler = 
				new UserInvocationHandler(userService);
		UserService userService1 = (UserService)Proxy.newProxyInstance(
				userService.getClass().getClassLoader(),
				userService.getClass().getInterfaces(),
				invocationHandler);
		userService1.hello("hello");
	}
}
public class UserInvocationHandler implements InvocationHandler {
	private Object tageet;

	public UserInvocationHandler() {
	}

	public UserInvocationHandler(Object tageet) {
		this.tageet = tageet;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		System.out.println("before-----"+method.getName());
		method.invoke(tageet,args);
		System.out.println("after-----"+method.getName());
		return null;
	}
}

public interface UserService {
	void hello(String str);
}

public class UserServiceImpl implements UserService {
	@Override
	public void hello(String name) {
		System.out.println(name + " world");
	}
}

运行结果:

before-----hello
hello world
after-----hello
    原文作者:AOP
    原文地址: https://blog.csdn.net/stay_the_course/article/details/84639741
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞