我刚刚学习了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();
    }
}

当我运行该项目时,我会遇到这样的错误



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

最佳答案

尝试仅从@Autowired中的setFood()中删除PecintaKuliner
喜欢

@Autowired
@Qualifier("nasigoreng")
private Food food;

public void setFood(Food food) {
    this.food = food;
}

关于java - Spring中的@Qualifier注释不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20159220/

10-10 09:41