Spring AOP concept
- (1) AOP (Aspect Oriented Programming) is aspect-oriented programming.
It is a technology预编译
that动态代理
realizes the unified maintenance of program functions through mode and operation .
Simply put, on the basis of not changing the original code of the method, the function enhancement of the method
essentially generates a new class called代理类
- (2) AOP adopts a dynamic proxy method for program expansion. (
JDK动态代理
andCglib动态代理
two methods)
Spring dynamic proxy
- (1) JDK dynamic proxy
"method of the
Proxy class static method of the Proxy class can create proxy objects
static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
" three parameters
Parameter 1:ClassLoader loader
Class loader, used to load the proxy object
Parameter 2:Class<?>[] interfaces
Bytecode object array of the target class. Because The proxy is an interface, and you need to know all the methods in the interface.Parameter
3:InvocationHandler h
Execution handle, the core logic of proxy object processing is in this interface - (2) Case: CEOs eat,
CEOs,
secretary
TestJDKProxy
public class TestJDKProxy {
@Test
public void Test02(){
//Jdk代理
//ILaoZong
final LaoZong laoZong = new LaoZong();
final MiShu miShu = new MiShu();
//1 创建一个代理类,创建该类的对象
ClassLoader classLoader = LaoZong.class.getClassLoader();
Class[] interfaces= new Class[]{
ILaoZong.class};
//处理器
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//调 laibeijiu()
miShu.laiBeiJiu();
//调 eat()
//laoZong.eat();
//method 被增加的方法
Object returnValue = method.invoke(laoZong,args);
//调 laiGenYan()
miShu.laiGenYan();
return returnValue;
}
};
ILaoZong iLaoZong = (ILaoZong) Proxy.newProxyInstance(classLoader,interfaces,handler);
iLaoZong.eat();
}
}
ILaoZong
public interface ILaoZong {
void eat();
}
LaoZong
public class LaoZong implements ILaoZong {
@Override
public void eat() {
System.out.println("eat san xia guo");
System.out.println("eat wa wa cai");
}
}
MiShu
public class MiShu {
public void laiBeiJiu(){
System.out.println("laiBeiJiu");
}
public void laiGenYan(){
System.out.println("laiGenYan");
}
}
Execute test result