Java implements AOP programming

Anyone who knows Spring knows Spring's Aspect Oriented Programming (AOP). Here we will not talk about Spring's aspect. We will dissect Spring's aspect programming later. We want to explain how to implement AOP in ordinary Java code. There are two There are two ways to implement the AOP aspect, one is the native SDK implementation, and the other is based on the tripartite package cglib.
First introduce the JDK native, which is based on interface programming:
first define an interface:
public interface ISayHelloWorld { public String say(); } Implement this interface: public class ManSayHelloWorld implements ISayHelloWorld {



 @Override
    public String say() {
        System.out.println("Hello world!");
        return "MAN";
    }

} To
realize the aspect proxy of ManSayHelloWorld, the native AOP needs to implement the InvocationHandler interface to realize AOP.
public class SayHello { public void say(){ System.out.println("hello world!"); } } import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method;





public class AOPHandle implements InvocationHandler {

 private Object obj;
    AOPHandle(Object obj){
        this.obj = obj;
    }
@Override
public Object invoke(Object proxy, Method method, Object[] args)
		throws Throwable {
	// TODO Auto-generated method stub
	//方法返回值
    System.out.println("前置代理");
    //反射调用方法
    Object ret=method.invoke(obj, args);
    //声明结束
    System.out.println("后置代理");
    //返回反射调用方法的返回值
    return ret;
}

}
Test this code:
import java.lang.reflect.Proxy;

public class Main {
public static void main(String[] args) {
ManSayHelloWorld sayHelloWorld = new ManSayHelloWorld();
AOPHandle handle = new AOPHandle(sayHelloWorld);
ISayHelloWorld i = (ISayHelloWorld) Proxy.newProxyInstance(ManSayHelloWorld.class.getClassLoader(), new Class[] { ISayHelloWorld.class }, handle);
i.say();
}
}
Insert picture description here
CSDN:java AOP编程

Guess you like

Origin blog.csdn.net/m0_38127487/article/details/113913358