亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 AOP 功能添加到 Spring 項目后沒有發現符合條件的 Bean 錯誤

將 AOP 功能添加到 Spring 項目后沒有發現符合條件的 Bean 錯誤

冉冉說 2023-03-23 15:01:08
我在向我的簡單項目添加 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();


查看完整回答
反對 回復 2023-03-23
  • 1 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號