gpt4 book ai didi

java - @qualifier 不能与 @Component 一起使用

转载 作者:行者123 更新时间:2023-11-30 02:58:50 28 4
gpt4 key购买 nike

大家好,我正在使用基于 Java 的配置,并且我有 2 个这样的类:

HelloWorld.Java

@Component
@Qualifier("hello")
public class HelloWorld {

public void helloWorld() {
System.out.println("hello world");
}
}

Main.java

public class Main {

public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("file:application-config.xml");

HelloWorld hw = (HelloWorld) context.getBean("hello");
hw.helloWorld();
}
}

应用程序配置.xml

<context:component-scan base-package="com.basepackage" />

这给了我以下错误:线程“main”org.springframework.beans.factory.NoSuchBeanDefinitionException中的异常:没有定义名为“hello”的bean

如果我使用 HelloWorld hw = context.getBean(HelloWorld.class) 它工作正常。

我在这里缺少什么?

最佳答案

@Qualifier 不会设置 bean 的名称,它只是向其中添加附加元数据。然而,getBean(String)期望 bean 名称作为其参数。您没有名为 hello 的 bean。

bean 的名称可以设置

@Component("hello")

在这种情况下,@Qualifier 在这种情况下变得毫无用处。

关于java - @qualifier 不能与 @Component 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36457325/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com