54_55 summarizes and analyzes the design principle and structure of the dynamic proxy class, And 54_55 dynamic
Log () is a system log. It can be modularized and hot-swappable by using the aspect programming to insert it around the invoke method.
For the previous code, the yellow part should be extracted and modularized.
Target Extraction as a parameter
final ArrayList target=new ArrayList();Collection proxy3 = (Collection) getProxy(target,new MyAdvice());
System functions are extracted into an object.
public static Object getProxy(final Object target,final Advice advice) { Object proxy3 = Proxy.newProxyInstance( Collection.class.getClassLoader(), new Class[]{Collection.class}, new InvocationHandler(){ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { advice.beforeMethod(method); Object reVal=method.invoke(target, args); advice.afterMethod(method); return reVal; } } ); return proxy3;}
Notification interface-Contract
package com.itcast.day3;import java.lang.reflect.Method;public interface Advice { public void beforeMethod(Method method); public void afterMethod(Method method);}
Implementation of the contract-usually the most workload when Spring aop is used at work
package com.itcast.day3;import java.lang.reflect.Method;public class MyAdvice implements Advice { long beginTime=0; @Override public void beforeMethod(Method method) { beginTime=System.currentTimeMillis(); } @Override public void afterMethod(Method method) { long endTime=System.currentTimeMillis(); System.out.println(method.getName()+" running "+(endTime-beginTime)); }}
When using spring aop, you only need to do two things.
1. Configure Advice
2. Configure target