容器介面 BeanFactory 是ApplicationContext的父介面,所有ApplicationContext的實現都組合了BeanFactory。 BeanFactory才是Spring的核心容器。 從BeanFactory提供的方法來看,主要是從容器中獲取Bean。實際上控制反轉,依 ...
分析:
當引入AOP相關依賴後
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </dependency>
Spring啟動時會載入AopAutoConfiguration
這個類中通過@EnableAspectJAutoProxy註解開啟AOP,代碼如下
點進去看看:
可以看到該註解是通過proxyTargetClass參數來控制是否使用Cglib動態代理的,預設值為false,即使用JDK動態代理
驗證一下:
public interface MyService { void say(); }
@Component public class MyServiceImpl implements MyService{ @Override public void say() { System.out.println("123"); } }
@Aspect @Component public class AOPTest { @Before("execution(* demo.aop.MyServiceImpl.say(..))") public void beforeSay() { System.out.println("hello"); } }
測試類:
@RunWith(SpringRunner.class) @SpringBootTest(classes = DemoApplication.class) public class AOPTest { @Autowired MyService myService; @Test public void test() { myService.say(); } }
debug執行:
嗯?並不是JDK動態代理,用的是Cglib動態代理,跟我們第二張圖看到的預設值不一樣哎
此時返回去看第一張圖,發現 @ConditionalOnProperty 註解下有屬性 matchIfMissing = true,即在缺少 proxy-target-class 配置的情況下,會匹配 CglibAutoProxyConfiguration,使用 @EnableAspectJAutoProxy(proxyTargetClass = true),就是使用Cglib動態代理
結論:
SpringBoot 2.x AOP預設使用的是Cglib動態代理
附加:
【一句話】@Configuration和@Component的區別
![](https://common.cnblogs.com/images/loading.gif)