java 1种以上注射用组分[一式两份]

siotufzp  于 5个月前  发布在  Java
关注(0)|答案(1)|浏览(38)

此问题在此处已有答案

Required Multiple beans of same type in Spring(3个答案)
4天前关闭。
我试图完全了解依赖注入机制,以及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 的实现。

piok6c0g

piok6c0g1#

在你的位置“cat”/“dog”中,使用@ browser注解,并指定实现的名称(从小写字母开始)!

相关问题