我正在开发一个Sping Boot 应用程序,其中我有一个Parent和一个Child类,Child扩展了Parent类。我正在为这两个类使用@Component
注解,以便能够通过Spring管理它们的示例。
@Component
public class Parent {}
@Component
public class Child extends Parent{}
字符串
这将导致NoUniqueBeanDefinitionException
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.example.Parent' available: expected single matching bean but found 2: Parent,Child
在Parent类上使用@Primary
解决了这个问题,但我想知道在上述场景中遵循的最佳实践或推荐方法是什么?
编辑:父类已经存在,并且正在使用@Resource(type = Parent.class)
注入到多个类中。我正在新添加Child类,并且希望尽可能不修改现有代码。
2条答案
按热度按时间yxyvkwin1#
在这里你可以看到你有两个相同类型的bean,所以spring无法区分首先注入哪一个。根据你说的解决方案,我们可以使用@primary annotation来解决这个问题。通过tht spring将能够理解哪一个是主要的或者哪一个应该首先注入。或者我们可以使用@qualifer annotaion下的@Autowire来指定你想要注入的bean名称。
xcitsw882#
make Parent class abstract:
字符串