Spring配置文件注入:不要在没有配置文件的情况下注入类

ecb*_*die 2 java spring dependency-injection spring-mvc

假设我在Java项目中使用Spring,并且具有以下接口和类:

public interface MyInterface { ... }

@Component
public class MyInterfaceMainImpl implements MyInterface { ... }

@Component
@Profile("mock")
public class MyInterfaceMockImpl implements MyInterface { ... }

@ContextConfiguration(locations = {"classpath:my-context.xml"})
@ActiveProfiles(profiles = {"mock"})
public class MyInterfaceTest extends AbstractTestNGSpringContextTests {
    @Inject
    private MyInterface myInterface;
    ...
}
Run Code Online (Sandbox Code Playgroud)

假设my-context.xml对包含我的接口及其实现类的包启用了组件扫描。当我将概要文件指定为“模拟”时,出现类似以下内容的错误:“期望单个匹配的Bean,但找到了2:...”。

知道如何避免在注入过程中使我的非概要文件方法成为匹配的bean吗?还是唯一可以为主要实现类提供配置文件的解决方案?那是我试图避免的解决方案。

axt*_*avt 5

有两种选择:

  • 使用@Primary,以指示MyInterfaceMockImpl当两个实施方式是本优选:

    @Component
    @Primary
    @Profile("mock")
    public class MyInterfaceMockImpl implements MyInterface { ... }
    
    Run Code Online (Sandbox Code Playgroud)
  • @Profile与否定一起使用可在mock活动时排除主要实现:

    @Component
    @Profile("!mock")
    public class MyInterfaceMainImpl implements MyInterface { ... }
    
    Run Code Online (Sandbox Code Playgroud)