参考图灵课堂-周瑜老师的视频做的笔记
动态代理分为jdk动态代理和cglib动态代理
jdk动态代理是实现被代理对象的接口,cglib是继承被代理对象
springAop默认是使用cglib来进行代理的
一个简单的aop的demo
@Component
public class PriceService {}
@Component
public class ProductService {
@Autowired
private PriceService priceService;
public void test(){
System.out.println(priceService);
}
}
@Aspect
@Component
public class Aop {
@Before("execution(public void com.example.demo.aop.ProductService.test())")
public void logBeforeController(JoinPoint joinPoint) {
System.out.println("=============调用了Before方法=============");
}
}
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
ProductService productServiceProxy = (ProductService) applicationContext.getBean("productService");
productServiceProxy.test(); //这里走了代理 ,并且priceService有值
//如何实现:productServiceProxy自己有个test方法并且里面有个target是真正的productService(它里面有priceService),但productServiceProxy自己本身的priceService还是空
}
}
代理类大致代码:
//使用cglib代理生成一个类
public class ProductServiceProxy extends ProductService {
/**
* 既然声明了ProductService,为什么还要继承他
* 不继承的话 在applicationContext.getBean("productService")时无法强转为ProductService,只能是ProductServiceProxy类型
*/
//注入ProductService对象
private ProductService target;
/**
* 为什么不调用super.test()
* 直接调用super.test()priceService为null,因为这个代理对象并没有进行依赖注入priceService,所以声明了一个ProductService(它已经在spring中进行创建并依赖注入)
*/
@Override
public void test() {
//1.切面逻辑@before
//2.执行对应的逻辑
target.test();
}
}