【发布时间】:2019-07-20 06:29:45
【问题描述】:
在我的 yaml 文件中,我的配置值如下:
myapp:
rest-clients:
rest-templates:
- id: myService1
username: chris
password: li
base-url: http://localhost:3000/service1
read-timeout: 2s
connect-timeout: 1s
- id: myService2
username: chris
password: li
base-url: http://localhost:3000/service1
read-timeout: 2s
connect-timeout: 1s
我希望 Spring Boot 2 应用为每个配置项注册一个 RestTemplate。
我的配置是bean如下:
@Configuration
@AllArgsConstructor
public class MyAppRestClientsConfiguration {
private MyAppRestClientsProperties properties;
private GenericApplicationContext applicationContext;
private RestTemplateBuilder restTemplateBuilder;
@PostConstruct
public void init() {
properties.getRestTemplates().forEach(this::registerRestTemplate);
}
private void registerRestTemplate(MyAppRestTemplateConfig config) {
// do some work
applicationContext.registerBean(config.getId(), RestTemplate.class, () -> restTemplate)
}
}
问题是当我通过@Autowire 注入我注册的RestTemplate 时,这个配置bean 还没有完成初始化。所以没有可以注入 RestTemplate bean。
@Autowired
@Qualifier("myService1")
private RestTemplate client1;
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
- @org.springframework.beans.factory.annotation.Qualifier(value=myService1)
有没有正确的方法来实现这个要求?
【问题讨论】:
-
你在哪里注入你的休息模板。
-
你应该试试@DependsOn注解。如需更清晰,请参阅docs.spring.io/spring-framework/docs/current/javadoc-api/org/…
-
@Thomas 我在一些控制器中注入了我的 resttemplate。
-
@P singh 我正在为我的团队实现一个库。所以不知道其他开发人员在哪里注入了 resttmplate。我希望他们拥有 conf yaml,然后可以将 resttempalte 注入任何 bean,就像 spring boot 为我们所做的那样。我不想强迫他们在需要休息模板时使用 @DependsOn 注释
标签: spring spring-boot