AOP底层实现
- Spring在运行期,生成动态代理对象,不需要特殊的编辑器
- Sping AOP的底层就是通过JDK动态代理或者CGLib动态代理技术为目标Bean执行横向织入
- 若目标对象实现了若干接口,Spring使用JDK的java.lang.reflect.Proxy类代理
- 诺目标对象没有实现任何接口,Spring使用CGLib库生成目标对象的子类
程序中应优先对接口创建代理,便于程序解耦维护=>面向接口编程规范
标记为final的方法,不能被代理,因为无法重写覆盖
- JDK动态代理,是针对接口生成子类,接口中方法不能使用final修饰
- CGLib是针对目标类继承子类,因此类或方法不能使用final修饰
另外Spring只支持方法连接点,不提供属性连接
JDK动态代理
//MyJDKProxy
public class MyJDKProxy implements InvocationHandler {
private UserDao userDaoimpl;
public MyJDKProxy(UserDao userDaoimpl) {
this.userDaoimpl = userDaoimpl;
}
public Object createProxy(){
Object proxy = Proxy.newProxyInstance(userDaoimpl.getClass().getClassLoader(), userDaoimpl.getClass().getInterfaces(), this);
return proxy;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("save".equals(method.getName())){
System.out.println("权限验证代码");
return method.invoke(userDaoimpl, args);
}
return method.invoke(userDaoimpl, args);
}
}
//UserDaoImpl
public class UserDaoImpl implements UserDao {
@Override
public void save(User user) {
System.out.println("保存用户");
}
@Override
public void update(User user) {
System.out.println("修改用户");
}
@Override
public void findAll() {
System.out.println("查询用户");
}
@Override
public void delete(Long id) {
System.out.println("删除用户");
}
}
//Proxy_Test
public class Proxy_Test {
@Test
public void myJDKProxy(){
UserDao userDaoImpl = new UserDaoImpl();
UserDao proxy = (UserDao) new MyJDKProxy(userDaoImpl).createProxy();
proxy.save(new User());
}
}
Cglib动态代理
//在使用CgLib时需要导入Spring基础包
//MyCglib
public class MyCglib implements MethodInterceptor {
private ProductDao productDaoImpl;
public MyCglib(ProductDao productDaoImpl) {
this.productDaoImpl = productDaoImpl;
}
public Object createProxy(){
//1.创建核心对象
Enhancer enhancer = new Enhancer();
//2.设置父类
enhancer.setSuperclass(productDaoImpl.getClass());
//3.设置回调方法
enhancer.setCallback(this);
//4.创建代理对象
Object proxy = enhancer.create();
return proxy;
}
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
if("save".equals(method.getName())){
System.out.println("权限验证中...");
return methodProxy.invoke(productDaoImpl, args);
}
return methodProxy.invoke(productDaoImpl, args);
}
}
//ProductDaoImlp
public class ProductDaoImlp implements ProductDao {
@Override
public void save(Product Product) {
System.out.println("保存");
}
@Override
public void update(Product Product) {
System.out.println("修改");
}
@Override
public void findAll() {
System.out.println("查询");
}
@Override
public void delete(Long id) {
System.out.println("删除");
}
}
//MyCglib_Test
public class MyCglib_Test {
@Test
public void MyCglib(){
ProductDao productDaoImlp = new ProductDaoImlp();
ProductDao proxy = (ProductDao)new MyCglib(productDaoImlp).createProxy();
proxy.save(new Product());
}
}
网友评论