为了账号安全,请及时绑定邮箱和手机立即绑定

将 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 关注
  • 96 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信