我在向我的簡單項目添加 AOP 功能時出現以下錯誤,有人可以為我解釋一下嗎?我還在下面提到了代碼的相關部分。Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.AOP.Car' available at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:346) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:337) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1123) at com.AOP.App.main(App.java:13)package com.AOP;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration; @Configuration@ComponentScan(basePackages = "com.AOP")public class AppConfig { }package com.AOP;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class App { public static void main( String[] args ) { ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); Car car = context.getBean(Car.class); car.drive(); }}package com.AOP;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Componentpublic class Car implements Vehicle{ @Autowired private Tyre tyre; public Tyre getTyre() { return tyre; } public void setTyre(Tyre tyre) { this.tyre = tyre; } public void drive() { System.out.println("driving a car"); System.out.println(tyre); }}package com.AOP;public interface Vehicle { void drive();}如果我在沒有實現“Vehicle”接口的情況下得到一個簡單的類“Car”,那么一切正常。但是添加該擴展名將導致 menterror。
1 回答

郎朗坤
TA貢獻1921條經驗 獲得超9個贊
這種行為在Spring 文檔中有很好的描述。你的情況正是:
如果被代理的目標對象至少實現了一個接口,則使用 JDK 動態代理。
您仍然可以通過名稱獲取 bean,并查看它的類是什么:
Object b = context.getBean("car"); System.out.println(b.getClass().getName());
它類似于com.sun.proxy.$Proxy38
,如果您嘗試瀏覽它的界面,它們com.AOP.Vehicle
之間就會有。
至此,為什么無法按類獲取bean就很清楚了。
該怎么辦 ?有一些選項:
使
Car
不實現Vehicle
(任何接口)。這樣,bean 將由 CGLIB 代理(并且其類保持不變),并且您的代碼將起作用通過向 annotation 添加以下屬性強制在任何地方使用 CGLIB 代理
@EnableAspectJAutoProxy(proxyTargetClass=true)
。您的代碼將起作用通過名稱獲取 bean(參見上面的代碼)
通過接口獲取bean:
Vehicle car = context.getBean(Vehicle.class); car.drive();
添加回答
舉報
0/150
提交
取消