2017-01-16 234 views
1

我有一个应用程序'app_test',它包含一个具有@Service注释的类TestClass。我有一个类库'lib_test',其中包含id为'TestClass'的XML文件中的bean。两者都有不同的包装。注入2个具有相同类名的bean

我米注入@Service豆如下

Import com.app.TestClass 

    Class TestController 
    { 
    Private final TestClass testClass; 

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

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

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

+0

可能的重复:http://stackoverflow.com/questions/3925681/spring-autowired-with-2-beans-of-the-same-type – pringi

+1

不是。它是一个具有相同的包和不同的名称。 M谈论不同的包和同名。 –

回答

1

虽然他们在不同的包,如果他们是同一类型的弹簧不知道用哪个

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

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

这样它将被选为默认自动装填候选者,而不需要另一个bean上的autowire-candidate。

另外,我发现使用@Resource来挑选特定的bean更优雅,而不是使用@Autowired @Qualifier

+2

它们不是同一类型。方法和一切都不一样,只是bean的名字是一样的。它没有给出重复的东西,因为没有找到bean。 –

1

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

这就是为什么我总是配置Spring项目不同BeanNameGenerator

public class CustomAnnotationConfigWebApplicationContext extends AnnotationConfigWebApplicationContext { 
    private BeanNameGenerator qualifiedAnnotationBeanNameGenerator = new QualifiedNameAnnotationBeanNameGenerator(); 

    @Override 
    protected BeanNameGenerator getBeanNameGenerator() { 
     return this.qualifiedAnnotationBeanNameGenerator; 
    } 
} 

和发电机:

public class QualifiedNameAnnotationBeanNameGenerator extends AnnotationBeanNameGenerator { 

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

有了这个设置,是在不同的包中常见的类名自动识别作为不同的和正确的一个被注入。

相关问题