Dynamic proxy simulation to implement aop and Dynamic Simulation of aop
The implementation of AOP code is quite simple. The main core is dynamic proxy and reflection.
I. interface class:
public interface MethodDao { public void sayHello();}
Ii. Interface implementation class:
public class MethodImpl implements MethodDao { public void sayHello() { System.out.println("hello world"); }}
3. Write a dynamic proxy class DynamicProxy and *** implement the InvocationHandler Interface
Public class DynamicProxy implements InvocationHandler {private Object object;/*** <p> Title: </p> * <p> Description: </p> * accept the proxy class */public DynamicProxy (Object object) {this. object = object; // TODO Auto-generated constructor stub}/* (non-Javadoc) * @ see java. lang. reflect. invocationHandler # invoke (java. lang. object, java. lang. reflect. method, java. lang. object []) * implements the invoke Method. After the method is executed, add the operation */public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {// TODO Auto-generated method stub System. out. println ("===== before method execution ======="); method. invoke (object, args); System. out. println ("===== after the method is executed ======"); return null ;}}
4. Compile the test class:
Public class Test {public static void main (String [] args) {MethodDao methodDao = new MethodImpl (); InvocationHandler handler = new DynamicProxy (methodDao ); // The first parameter is the class loader, which is the same as handler; // The second parameter is the interface implemented by the parameter object. If not, use cdlib // and the third parameter is InvocationHandler. // This class actually returns MethodImpl class methodDao = (MethodDao) Proxy. newProxyInstance (handler. getClass (). getClassLoader (), methodDao. getClass (). getInterfaces (), handler); methodDao. sayHello ();}}
5. view the console output:
===== Before method execution ========
Hello world
===== After method execution ========
6. Summary:
The above code summarizes the application scenarios of AOP:
1. Transaction Management (the opening and submission of a transaction can be directly handled by aop, and programmers can focus more on the Business)
2. Log Management (logs can be printed before and after method calls)
3. permission management (for example, logon verification, Administrator permission, etc. If you have insufficient permissions when calling a method, you can also prompt ).