简体   繁体   English

在Spring中自动连线特定的内部bean

[英]Autowire specific inner bean in Spring

I have an interface called HttpClient , and two beans implementation of the bean, 我有一个名为HttpClient的接口,以及该bean的两个beans实现,

 public interface HttpClient {
    String bla();
}


@Component
public class HttpClientImpl implements HttpClient {
    @Override
    public String bla() {
        return null;
    }
}


@Component
public class HttpClientMock implements HttpClient {
    @Override
    public String bla() {
        return null;
    }
}

And now I have a wrapper for this bean that injects the HttpClient 现在,我有这个bean的包装器,该包装器注入了HttpClient

@Component
public class Wrapper {
    @Autowired HttpClient httpClient;
}

Is there any way to choose when I inject the Wrapper 当我注入Wrapper时,有什么选择吗

@Autowired Wrapper wrapper;

to choose the specific implementation for the HttpClient , I mean if I want to inject the HttpClientMock ? 选择HttpClient的特定实现,我的意思是是否要注入HttpClientMock

@Component("httpClient")
public class HttpClientImpl implements HttpClient {
    @Override
    public String bla() {
        return null;
    }
}

@Component("httpClientMock")
public class HttpClientMock implements HttpClient {
    @Override
    public String bla() {
        return null;
    }
}

@Component
public class Wrapper {
    @Autowired
    @Qualifier("httpClient")
    HttpClient httpClient;

    @Autowired
    @Qualifier("httpClientMock")
    HttpClient httpClientMock;
}

Here it seems you need your httpClient for testing, In that case i wouldnt say to do above way, rather create profiles as given below (you can have different profile for other ones) and when you run your spring application , run it in test profile. 在这里,您似乎需要您的httpClient进行测试,在这种情况下,我不会说要按照上述方式进行操作,而是按以下方式创建配置文件(您可以为其他配置文件创建不同的配置文件),并且在运行spring应用程序时,在测试配置文件中运行它。 Find more information about spring profiles here 在此处找到有关弹簧轮廓的更多信息

@Component("httpClientMock")
@Profile("test")
public class HttpClientMock implements HttpClient {
    @Override
    public String bla() {
        return null;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM