注射超过 1 个成分

问题描述 投票:0回答:1

我正在尝试完全了解依赖注入机制,以及 IoC 容器的功能。 我创建了一个带有界面的简单项目及其实现:

public interface Animal {
    public void makeSound();
}

@Component
public class Dog implements Animal {
    @Override
    public void makeSound() {
        System.out.println("Woof woof");
    }
}

@Component
public class Cat implements Animal {
    @Override
    public void makeSound() {
        System.out.println("Meow meow");
    }
}

Animal接口的对象正在另一个类中使用和自动装配,然后所有内容都在Main中初始化:

@Repository public class Shelter { private Animal animal; @Autowired public Shelter(Animal animal) { this.animal = animal; } public void doTheThing() { animal.makeSound(); } } @SpringBootApplication public class Main{ public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(Main.class); Shelter shelter = context.getBean(Shelter.class); Shelter anotherShelter = context.getBean(Shelter.class); shelter.doTheThing(); anotherShelter.doTheThing(); } }
现在,如果 

Animal 接口的实现之一没有 @Primary 注解,编译会抛出错误,因为 Spring 不知道要使用哪个实现。我明白这一点。 但现在我想知道,如何向 shelteranotherShelter 字段“private Animal Animal”注入不同的实现(当然通过构造函数注入)?有可能吗?换句话说:我想让shelter使用Dog的实现,而anotherShelter使用Cat的实现。 先谢谢你了

java spring dependency-injection
1个回答
0
投票
使用@Qualifier注释,并在你的情况“cat”/“dog”中指定实现的名称(以小写开头)!

© www.soinside.com 2019 - 2024. All rights reserved.