一、目标对象和代理对象
目标对象:在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代理使用的为继承,所有产生的代理对象等同于目标对象