注入2个具有相同类名的bean

时间:2017-01-16 16:19:25

标签: spring spring-boot autowired

我有一个应用' app_test'它包含一个带有@Service anotation的类TestClass。我有一个图书馆课程' lib_test'使用bean在XML文件中使用id ='' TestClass'。两者都在不同的包装中。

我按如下方式注入@Service bean

Import com.app.TestClass

    Class TestController
    {
    Private final TestClass testClass;

    @Inject
    TestController  (TestClass testClass)
    {
      This.testClass =testClass;
    }
    }

它应该按类型注入,因为它们在不同的包中。但控制器正在提供未找到合格的bean。

我可以通过给@Qualifier并给@Service命名来解决它。但是你需要吗?由于两者都在不同的包中,它应该按类型自动装配吗?或者我错过了一些概念?

2 个答案:

答案 0 :(得分:1)

虽然它们属于不同的包,但如果它们属于同一类型,则Spring不知道使用哪个

我建议使用@Primary标记任何服务类。

package com.app.TestClass
@Primary
@Repository
public class TestClass implements XXX

这样它将被选为默认的autowire候选者,不需要在另一个bean上使用autowire候选者。

此外,我发现使用@Autowired @Qualifier来挑选特定的bean,而不是使用@Resource,而不是typedef decltype(f<0>) t; using g1 = decltype(f<0>);

答案 1 :(得分:1)

我总是发现这是Spring标准bean命名约定的一个奇怪限制。当类具有相同名称时,它不包括名称中类的包部分,导致大型项目中的重复项。

这就是为什么我总是使用不同的public class CustomAnnotationConfigWebApplicationContext extends AnnotationConfigWebApplicationContext { private BeanNameGenerator qualifiedAnnotationBeanNameGenerator = new QualifiedNameAnnotationBeanNameGenerator(); @Override protected BeanNameGenerator getBeanNameGenerator() { return this.qualifiedAnnotationBeanNameGenerator; } } 配置Spring项目:

public class QualifiedNameAnnotationBeanNameGenerator extends AnnotationBeanNameGenerator {

    @Override
    protected String buildDefaultBeanName(BeanDefinition definition) {
        String qualifiedName = definition.getBeanClassName();
        return Introspector.decapitalize(qualifiedName);
    }
}

发电机:

-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable

通过此设置,不同包中的常见类名会自动识别为不同,并且会注入正确的类名。