Spring AOP教程(spring aop 一)

jdk中的动态代理

  • 一个是原有类,一个是拦截器增强类
  • 通过代理类增强原有类的功能

Spring AOP教程(spring aop 一)

代码实现

public interface RoleService {
	void print(Object obj);
}

public class RoleServiceImpl implements RoleService {
	@Override
	public void print(Object obj) {
		System.out.println("role 123");
		obj.toString();
	}
}

拦截器(增强类)

public interface Interceptor {
	void before(Object obj);
	void after(Object obj);
	void afterReturning(Object obj);
	void afterThrowing(Object obj);
}

public class RoleInterceptor implements Interceptor {
	@Override
	public void before(Object obj) {
		System.out.println("before");
	}

	@Override
	public void after(Object obj) {
		System.out.println("after");
	}

	@Override
	public void afterReturning(Object obj) {
		System.out.println("afterReturning");
	}

	@Override
	public void afterThrowing(Object obj) {
		System.out.println("afterThrowing");
	}
}

代理类

public class ProxyBeanFactory {
	public static <T> T getBean(T obj, Interceptor interceptor) {
		return (T) Proxy.newProxyInstance(ProxyBeanFactory.class.getClassLoader(), obj.getClass().getInterfaces(),
				new RoleInvocationHandler<>(obj, interceptor));
	}
}

public class RoleInvocationHandler<T> implements InvocationHandler {
	
	private T obj;
	private Interceptor intercept;
	
	public RoleInvocationHandler(T obj, Interceptor intercept) {
		this.obj = obj;
		this.intercept = intercept;
	}
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		intercept.before(obj);
		Object invoke = null;
		try {
			invoke = method.invoke(obj, args);
			intercept.after(obj);
			intercept.afterReturning(obj);
		} catch (Exception e) {
			intercept.after(obj);
			intercept.afterThrowing(obj);
			e.printStackTrace();
		}
		
		return invoke;
	}

}

测试类

public class GameMain {
	public static void main(String[] args) {
		RoleService service = new RoleServiceImpl();
		Interceptor interceptor = new RoleInterceptor();
		RoleService proxy = ProxyBeanFactory.getBean(service, interceptor);
		proxy.print("x");
		System.out.println("=======================");
		proxy.print(null);
	}
}

运行结果

before
role 123
after
afterReturning
=======================
before
role 123
after
afterThrowing
java.lang.reflect.InvocationTargetException
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at priv.dengjl.spring.day3.game.invocation.RoleInvocationHandler.invoke(RoleInvocationHandler.java:22)
	at com.sun.proxy.$Proxy0.print(Unknown Source)
	at priv.dengjl.spring.day3.game.GameMain.main(GameMain.java:16)
Caused by: java.lang.NullPointerException
	at priv.dengjl.spring.day3.game.service.RoleServiceImpl.print(RoleServiceImpl.java:11)
	... 7 more

实现代理功能,以下为spring aop的演进