SpringBoot:如何注入两个具有相同名称的类

Phi*_*EUR 5 spring dependency-injection guice spring-boot

在我的应用程序中,我有两个具有相同名称的类,但当然位于不同的包中。

这两个类都需要注入到应用程序中;不幸的是,我收到以下错误消息:

Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'myFeature' for bean class [org.pmesmeur.springboot.training.service.feature2.MyFeature] conflicts with existing, non-compatible bean definition of same name and class [org.pmesmeur.springboot.training.service.feature1.MyFeature]
Run Code Online (Sandbox Code Playgroud)

我的问题可以通过以下示例重现:

@Component
@EnableConfigurationProperties(ServiceProperties.class)
public class MyService implements IService {

    private final ServiceProperties serviceProperties;
    private final IProvider provider;
    private final org.pmesmeur.springboot.training.service.feature1.IMyFeature f1;
    private final org.pmesmeur.springboot.training.service.feature2.IMyFeature f2;


    @Autowired
    public MyService(ServiceProperties serviceProperties,
                     IProvider provider,
                     org.pmesmeur.springboot.training.service.feature1.IMyFeature f1,
                     org.pmesmeur.springboot.training.service.feature2.IMyFeature f2) {
        this.serviceProperties = serviceProperties;
        this.provider = provider;
        this.f1 = f1;
        this.f2 = f2;
    }
    ...
Run Code Online (Sandbox Code Playgroud)
package org.pmesmeur.springboot.training.service.feature1;

public interface IMyFeature {

    void print();

}
Run Code Online (Sandbox Code Playgroud)
package org.pmesmeur.springboot.training.service.feature1;

import org.springframework.stereotype.Component;

@Component
public class MyFeature implements IMyFeature {

    @Override
    public void print() {
        System.out.print("HelloWorld");
    }

}
Run Code Online (Sandbox Code Playgroud)
package org.pmesmeur.springboot.training.service.feature2;

public interface IMyFeature {

    void print();

}
Run Code Online (Sandbox Code Playgroud)
package org.pmesmeur.springboot.training.service.feature2;

import org.springframework.stereotype.Component;


@Component
public class MyFeature implements IMyFeature {

    @Override
    public void print() {
        System.out.print("FooBar");
    }

}
Run Code Online (Sandbox Code Playgroud)

如果我为我的课程使用不同的名称MyFeature,我的问题就会消失!

我习惯使用 Guice,这个框架没有这种问题/限制

似乎 spring 依赖项注入框架仅使用类名而不是包名 + 类名来选择其类。

在“现实生活”中,我在一个更大的项目中遇到了这个问题,我强烈希望不必重命名我的类:任何人都可以帮助我吗?

最后一点,我宁愿避免“技巧”,例如 @Qualifier(value = "ABC")在注入我的类时使用:在我的示例中,查找正确的实例不应该有歧义, MyFeature因为它们没有实现相同的接口

Mic*_*ski 0

您可以为每个组件分配一个值,例如@Component(value="someBean"),然后用@Qualifier例如注入它

@Autowired
public SomeService(@Qualifier("someBean") Some s){
   //....
}
Run Code Online (Sandbox Code Playgroud)