我遇到了來自Spring的非常奇怪的行爲。我有一個@Bean
它返回一個地圖。但是,當Bean爲@Autowired
時,地圖的關鍵字與在@Bean
方法中分配的關鍵字不同。我的@Bean
有兩個輸入參數,它們也是來自另一個配置類的Spring Beans。一旦@Autowired
我的地圖的鍵被更改爲匹配@Bean
方法的名稱,作爲依賴項傳遞給我的Map返回Bean。有問題的@Bean
位於@ConfigurationProperties
類中,我從我的application.yml文件中提取了一些值,這些值都正確返回。彈簧不必要地修改返回的Bean
@Component
@ConfigurationProperties(prefix = "channel-broker")
@EnableConfigurationProperties
public class ChannelLookupConfig {
private String messageDeliveryChannelKey;
private String otherDeliveryChannelKey;
public String getMessageDeliveryChannelKey() {
return messageDeliveryChannelKey;
}
public void setMessageDeliveryChannelKey(String messageDeliveryChannelKey) {
this.messageDeliveryChannelKey = messageDeliveryChannelKey;
}
public String getOtherDeliveryChannelKey() {
return otherDeliveryChannelKey;
}
public void setOtherDeliveryChannelKey(String OtherDeliveryChannelKey) {
this.otherDeliveryChannelKey = OtherDeliveryChannelKey;
}
@Bean
public Map<String, MessageDeliveryClient> channelCallerLookup(MessageDeliveryClient MessageDispatcherClient, MessageDeliveryClient otherDeliveryClient) {
Map<String, MessageDeliveryClient> channelCallerLookup = new HashMap<>();
channelCallerLookup.put(messageDeliveryChannelKey, MessageDispatcherClient);
channelCallerLookup.put(otherDeliveryChannelKey, otherDeliveryClient);
return channelCallerLookup;
}
}
我的第二個配置文件
@Configuration
public class Config {
@Bean
public MessageDeliveryClient MessageDispatcherClient() {
MessageDeliveryClient client = MessageDeliveryClient.builder()
.awsAccessKey(destinationSqsAccessKey)
.awsSecretKey(destinationSqsSecretKey)
.awsRegion(destinationSqsRegion)
.destinationQueueName(destinationSqsName)
.build();
return client;
}
@Bean
public MessageDeliveryClient otherPickerDeliveryClient() {
MessageDeliveryClient client = MessageDeliveryClient.builder()
.awsAccessKey(destinationSqsAccessKey)
.awsSecretKey(destinationSqsSecretKey)
.awsRegion(destinationSqsRegion)
.destinationQueueName(destinationOtherPickerSqsName)
.build();
return client;
}
}
自動裝配Autowired在用作這樣的:
public class SimpleCustomerMessageDeliveryBrokerImpl implements CustomerMessageDeliveryBroker {
private Map<String, MessageDeliveryClient> channelCallerLookup = new HashMap<>();
@Autowired
public void setBrokerConfiguration(BrokerConfiguration brokerConfiguration) {
this.brokerConfiguration = brokerConfiguration;
}
}
地圖應該包含2種元素的第一與鍵等於值在字符串messageDeliveryChannelKey
第二個關鍵字等於字符串otherDeliveryChannelKey
中的值。但是,這些鍵總是被設置爲等於傳入我的分數的@Beans方法的名稱。即使我將方法名稱改爲廢話,地圖的鍵也會等於該值。
如何防止這種現象的發生
一個'地圖<字符串,MessageDeliveryClient>'是春天,只要你想一個類型的所有豆類注入解釋那張地圖。關鍵是這個bean的名字。所以當使用你所得到的'Map'時。這是默認行爲,不能被轉換。 –
但是,您可以使用SimpleCustomerMessageDeliveryBrokerImpl類中的@Value註釋來讀取這些參數。 –
@FedericoJoséSorenson是的,這是我以前的實際。但是我試圖從那個類中提取出來,並且只給它Map,所以地圖本質上可以根據需要增長,並且每次添加新事物時,類都不會改變。 –