Spring中的@Qualifier注释不起作用

我刚刚学习了Spring Framework,并一直在使用Spring 2.5进行学习。我用这些类创建了三个bean

Food.java

package com.spring.danipetrick;

public interface Food {

void ingredients();

}

NasiGoreng.java

package com.spring.danipetrick;

public class NasiGoreng implements Food {

public NasiGoreng() {

}

public void ingredients() {

System.out.println("Rice, Coconut oil, Egg, Crackers");

}

@Override

public String toString() {

return "Nasi Goreng";

}

}

Rendang.java

package com.spring.danipetrick;

public class Rendang implements Food {

public void ingredients() {

System.out.println("Beef, Coconut milk, spices");

}

@Override

public String toString() {

return "Rendang";

}

}

PecintaKuliner.java

package com.spring.danipetrick;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

public class PecintaKuliner {

@Autowired

@Qualifier("nasigoreng")

private Food food;

@Autowired

public void setFood(Food food) {

this.food = food;

}

public Food getFood() {

return this.food;

}

public void sayMaknyus() {

System.out.println(food.toString() + " memang maknyus...");

}

}

XML配置,qualifier-test.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd">

<context:annotation-config />

<bean id="bondan" class="com.spring.danipetrick.PecintaKuliner">

</bean>

<bean id="rendang" class="com.spring.danipetrick.Rendang"/>

<bean id="nasigoreng" class="com.spring.danipetrick.NasiGoreng" />

</beans>

最后,具有main方法的类是QualifierTestMain.java:

package com.spring.danipetrick;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class QualifierTestMain {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("/qualifier-test.xml");

PencintaKuliner bondan = (PencintaKuliner)context.getBean("bondan");

bondan.sayMaknyus();

}

}

当我运行该项目时,出现这样的错误

由以下原因引起:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有定义[com.spring.danipetrick.Food]类型的唯一bean:期望的单个匹配bean,但发现2:[rendang,nasigoreng]

为什么@Qualifier注释在我的情况下不起作用?

回答:

尝试仅仅去除@Autowired来自setFood()PecintaKuliner

喜欢

@Autowired

@Qualifier("nasigoreng")

private Food food;

public void setFood(Food food) {

this.food = food;

}

以上是 Spring中的@Qualifier注释不起作用 的全部内容, 来源链接: utcz.com/qa/432408.html

回到顶部