interface
package com.shunli.ioc.demo5;
public interface UserDao {
public void save();
public void update();
public void find();
public void delete();
}
Implementation class
package com.shunli.ioc.demo5;
public class UserDaoImpl implements UserDao{
@Override
public void save() {
System.out.println("save........");
}
@Override
public void update() {
System.out.println("update........");
}
@Override
public void find() {
System.out.println("find........");
}
@Override
public void delete() {
System.out.println("delete........");
}
}
Dynamic proxy class
package com.shunli.ioc.demo5;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/*
* 动态代理类
*/
public class MyJdkProxy implements InvocationHandler{
UserDao userDao;
public MyJdkProxy(UserDao userDao) {
this.userDao =userDao;
}
public Object createProxy() {
Object object= Proxy.newProxyInstance(userDao.getClass().getClassLoader(), userDao.getClass().getInterfaces(), this);
return object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("update".equals(method.getName())) {
System.out.println("在调用update前调用....");
}
return method.invoke(userDao, args);
}
}
demo
package com.shunli.ioc.demo5;
import org.junit.Test;
public class Demo {
@Test
public void demo1() {
UserDao userDao = new UserDaoImpl();
UserDao proxy = (UserDao)new MyJdkProxy(userDao).createProxy();
proxy.save();
proxy.update();
proxy.find();
proxy.delete();
}
}
Print results
Spring at runtime, generate dynamic proxy object, no special compiler
Spring AOP is the underlying objective Bean performed by weaving transverse JDK dynamic proxy or a dynamic proxy technology CGLib
1. If the target object implements a number of interfaces, spring using JDK dynamic proxy
2. subclass if the target object does not implement any interfaces, spring CGLib libraries generated using the target object
The program should give priority to create an interface agent, to facilitate maintenance procedures decoupling,
edit method final and can not be agents, because they can not be covered
--JDK dynamic proxy, an interface is generated for a subclass, the method can not be used in the interface final modification, CGLIB is a subclass of the target class, or the class party can not use the final
--spring method only supports connection points, not for properties connection.