我正在嘗試RestTemplate為不同的組態檔加載不同的s。這是我如何實施它:
RestTemplateProviderConfiguration.java
package com.my.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import static org.apache.commons.lang.StringUtils.equalsIgnoreCase;
@Configuration
public class RestTemplateProviderConfiguration {
@Autowired
private ApplicationContext appContext;
@Value("${spring.profiles.active:}")
private String activeProfile;
@Value("${iam.rest.template:}")
private String iamRestTemplateQualifier;
@Bean
public RestTemplate restTemplate() {
return equalsIgnoreCase(activeProfile, "local") ? new RestTemplate() : (RestTemplate) appContext.getBean(iamRestTemplateQualifier);
}
}
服務.java
...
@Autowired
private RestTemplateProviderConfiguration restTemplateProviderConfiguration;
...
public void testRestClient() {
return restTemplateProviderConfiguration.restTemplate()
.exchange(...);
}
任何人都可以提出一個更好的方法,我可以使用:
@Autowire
RestTemplate restTemplate;
它會根據活動的彈簧輪廓加載正確的模板嗎?
uj5u.com熱心網友回復:
如果您使用的是 Spring 5.1.4 ,則可@Profile以為RestTemplatebean指定注釋。
@Bean
@Profile("local")
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
@Profile("!local")
public RestTemplate iamrestTemplate() {
return new RestTemplate();
}
有關此注釋,請參閱javadoc。
uj5u.com熱心網友回復:
@Configuration對于具有等效組態檔的每個組態檔, 您應該有 2 個不同的@Profile({"local"})
每個配置將回傳RestTemplate(和其他相關 bean)的不同實作
您還可以為每個 Bean定義Profile,但這可能會令人困惑
@Profile("profile") @Bean MyBean myBean(MyBeanProperties properties) {
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362165.html
上一篇:確定陣列中的最大數字
下一篇:檢查玩家是否在移動
