在 Spring 中,@Autowired
注解的使用在不同的上下文中會產(chǎn)生不同的效果,這取決于所在的組件或類是否由Spring管理。
-
@Aspect
注解的使用:@Aspect
注解通常用于聲明切面,而切面是 Spring 管理的組件。因此,@Autowired
注解可以直接用于切面類,以注入其他 Spring 托管的 bean。Spring AOP通過代理機(jī)制實現(xiàn),切面類被 Spring 托管,因此可以利用 Spring 的依賴注入功能。@Aspect @Component public class MyAspect { @Autowired private MyService myService; // ... }
-
InvocationHandler
接口的實現(xiàn)類:InvocationHandler
接口的實現(xiàn)類通常不是由 Spring 管理的,它們是標(biāo)準(zhǔn) Java 類。在這種情況下,Spring 的依賴注入機(jī)制不會自動生效,因為 Spring 無法感知和管理這些類。如果你在InvocationHandler
實現(xiàn)類中需要依賴注入的功能,你需要手動注入依賴或者在創(chuàng)建代理對象時進(jìn)行注入。文章來源:http://www.zghlxwxcb.cn/news/detail-695224.htmlpublic 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)依賴注入,而標(biāo)準(zhǔn) Java 類通常需要手動注入依賴。@Aspect
注解的類通常是由 Spring 管理的,因此可以使用 @Autowired
注解來注入其他組件。而 InvocationHandler
接口的實現(xiàn)類通常不是由 Spring 管理的,所以不能直接使用 @Autowired
注解。文章來源地址http://www.zghlxwxcb.cn/news/detail-695224.html
到了這里,關(guān)于springboot~aop方法攔截Aspect和InvocationHandler的理解的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!