springboot~aop方法攔截Aspect和InvocationHandler的理解
在 Spring 中,@Autowired 注解的使用在不同的上下文中會產(chǎn)生不同的效果,這取決于所在的組件或類是否由Spring管理。
-
@Aspect注解的使用:@Aspect注解通常用于聲明切面,而切面是 Spring 管理的組件。因此,@Autowired注解可以直接用于切面類,以注入其他 Spring 托管的 bean。Spring AOP通過代理機制實現(xiàn),切面類被 Spring 托管,因此可以利用 Spring 的依賴注入功能。@Aspect @Component public class MyAspect { @Autowired private MyService myService; // ... } -
InvocationHandler接口的實現(xiàn)類:InvocationHandler接口的實現(xiàn)類通常不是由 Spring 管理的,它們是標準 Java 類。在這種情況下,Spring 的依賴注入機制不會自動生效,因為 Spring 無法感知和管理這些類。如果你在InvocationHandler實現(xiàn)類中需要依賴注入的功能,你需要手動注入依賴或者在創(chuàng)建代理對象時進行注入。public class MyInvocationHandler implements InvocationHandler { private final MyService myService; public MyInvocationHandler(MyService myService) { this.myService = myService; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 在這里可以使用注入的 myService myService.doSomething(); // ... } }
總之,差異在于組件是否由 Spring 管理。Spring 管理的組件可以利用 @Autowired 注解來實現(xiàn)依賴注入,而標準 Java 類通常需要手動注入依賴。@Aspect 注解的類通常是由 Spring 管理的,因此可以使用 @Autowired 注解來注入其他組件。而 InvocationHandler 接口的實現(xiàn)類通常不是由 Spring 管理的,所以不能直接使用 @Autowired 注解。
浙公網(wǎng)安備 33010602011771號