SpringAOP学习笔记(一)——目标对象和代理对象

本文介绍了SpringAOP中的目标对象和代理对象。目标对象是指被SpringAOP增强的对象,而代理对象是在目标对象基础上,通过AOP增加额外逻辑产生的新对象。在使用接口的情况下,Spring默认采用JDK动态代理,代理对象继承Proxy并实现相同接口。启用@EnableAspectJAutoProxy(proxyTargetClass = true)则会切换到CGLIB代理,代理对象直接继承目标对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、目标对象和代理对象

目标对象:在SpringAOP被增强的对象

代理对象:通过aop中对目标对象进行增强,加入代理逻辑的而产生的对象

 

public interface Service  {
    void query();
}

@Repository
public class UserService implements Service {
    public void query() {
        System.out.println("user");
    }
}

@Configuration
@ComponentScan("com")
@EnableAspectJAutoProxy   //开启aspect注解,默认使用jdk动态代理
public class JavaConfig {
}

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
        UserService index =(UserService) context.getBean("userService");
         System.out.println(index instanceof UserService);
         System.out.println(index instanceof Proxy);
         System.out.println(index instanceof Service);
        
    }
}



//打印
false
true
true

如果一个对象实现了一个接口,在使用AOP对其进行增强时,将会产生一个新的代理对象,但是这个代理对象不会等于目标对象,因为在代理中,Spring默认使用jdk动态代理的方式去增强,也就是说在对目标对象织入时,会有jdk生成一个代理对象,该代理对象执行了原始对象中的逻辑,并在此基础上加入增强逻辑。

  //将动态代理生成的对象字节码读写出来
try {
            Class<?>[] interfaces = new Class[]{Service.class};
            byte[] proxyUserServices = ProxyGenerator.generateProxyClass("ProxyUserService", interfaces);
            FileOutputStream fileOutputStream = new FileOutputStream(new File("G:\\ProxyUserService.class"));
            fileOutputStream.write(proxyUserServices);
            fileOutputStream.flush();
            fileOutputStream.close();
        }catch (Exception e){
        }


//通过jdk动态代理动态生成的代理对象
public final class ProxyUserService extends Proxy implements Service {
    private static Method m1;
    private static Method m3;
    private static Method m2;
    private static Method m0;

    public ProxyUserService(InvocationHandler var1) throws  {
        super(var1);
   

    public final void query() throws  {
        try {
            super.h.invoke(this, m3, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }
    //...
 
}

由上可知,在使用jdk动态代理生成代理对象是一个继承了Proxy类并且实现了Service接口。

如果在配置类上加上@EnableAspectJAutoProxy(proxyTargetClass = true),表示修改AOP的实现方式为CGLIB代理,CGLIB代理使用的为继承,所有产生的代理对象等同于目标对象


 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值