Java 如何使用 @Value Spring Annotation 注入 Map?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30691949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to inject a Map using the @Value Spring Annotation?
提问by yathirigan
How can i inject values into a Map from the properties file using the @Value annotation in Spring ?
如何使用 Spring 中的 @Value 注释从属性文件中将值注入到 Map 中?
My Spring Java class is and i tried using the $ but, got the following error message
我的 Spring Java 类是,我尝试使用 $ 但是,收到以下错误消息
Could not autowire field: private java.util.Map Test.standard; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'com.test.standard' in string value "${com.test.standard}"
无法自动装配字段:private java.util.Map Test.standard; 嵌套异常是 java.lang.IllegalArgumentException:无法解析字符串值“${com.test.standard}”中的占位符“com.test.standard”
@ConfigurationProperty("com.hello.foo")
public class Test {
@Value("${com.test.standard}")
private Map<String,Pattern> standard = new LinkedHashMap<String,Pattern>
private String enabled;
}
I have the following properties in a .properties file
我在 .properties 文件中有以下属性
com.test.standard.name1=Pattern1
com.test.standard.name2=Pattern2
com.test.standard.name3=Pattern3
com.hello.foo.enabled=true
采纳答案by luboskrnac
I believe Spring Boot supports loading properties maps out of the box with @ConfigurationPropertiesannotation.
我相信 Spring Boot 支持使用@ConfigurationProperties注释开箱即用地加载属性映射。
According that docs you can load properties:
根据该文档,您可以加载属性:
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com
into bean like this:
像这样变成bean:
@ConfigurationProperties(prefix="my")
public class Config {
private List<String> servers = new ArrayList<String>();
public List<String> getServers() {
return this.servers;
}
}
I used @ConfigurationProperties feature before, but without loading into map. You need to use @EnableConfigurationProperties annotationto enable this feature.
我之前使用过 @ConfigurationProperties 功能,但没有加载到地图中。您需要使用@EnableConfigurationProperties 注解来启用此功能。
Cool stuff about this feature is that you can validate your properties.
这个功能很酷的一点是你可以验证你的属性。
回答by Arpit Aggarwal
You can inject .properties
as a map in your class using @Resource
annotation.
您可以.properties
使用@Resource
注释在类中作为地图注入。
If you are working with XML based configuration
,then add below bean in your spring configuration file:
如果您正在使用XML based configuration
,则在您的 spring 配置文件中添加以下 bean:
<bean id="myProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:your.properties"/>
</bean>
For, Annotation based:
对于,基于注解:
@Bean(name = "myProperties")
public static PropertiesFactoryBean mapper() {
PropertiesFactoryBean bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource(
"your.properties"));
return bean;
}
Then you can pick them up in your application as a Map:
然后您可以在您的应用程序中将它们作为 Map 提取:
@Resource(name = "myProperties")
private Map<String, String> myProperties;
回答by Michael Rahenkamp
You can inject values into a Map from the properties file using the @Value
annotation like this.
您可以使用这样的@Value
注释从属性文件中将值注入到 Map 中。
The property in the properties file.
属性文件中的属性。
propertyname={key1:'value1',key2:'value2',....}
In your code.
在你的代码中。
@Value("#{${propertyname}}") private Map<String,String> propertyname;
Note the hashtag as part of the annotation.
请注意将主题标签作为注释的一部分。
回答by Neil Han
Here is how we did it. Two sample classes as follow:
这是我们如何做到的。两个示例类如下:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
@EnableKafka
@Configuration
@EnableConfigurationProperties(KafkaConsumerProperties.class)
public class KafkaContainerConfig {
@Autowired
protected KafkaConsumerProperties kafkaConsumerProperties;
@Bean
public ConsumerFactory<String, String> consumerFactory() {
return new DefaultKafkaConsumerFactory<>(kafkaConsumerProperties.getKafkaConsumerConfig());
}
...
@Configuration
@ConfigurationProperties
public class KafkaConsumerProperties {
protected Map<String, Object> kafkaConsumerConfig = new HashMap<>();
@ConfigurationProperties("kafkaConsumerConfig")
public Map<String, Object> getKafkaConsumerConfig() {
return (kafkaConsumerConfig);
}
...
To provide the kafkaConsumer config from a properties file, you can use: mapname[key]=value
要从属性文件提供 kafkaConsumer 配置,您可以使用:mapname[key]=value
//application.properties
kafkaConsumerConfig[bootstrap.servers]=localhost:9092, localhost:9093, localhost:9094
kafkaConsumerConfig[group.id]=test-consumer-group-local
kafkaConsumerConfig[value.deserializer]=org.apache.kafka.common.serialization.StringDeserializer
kafkaConsumerConfig[key.deserializer=org.apache.kafka.common.serialization.StringDeserializer
To provide the kafkaConsumer config from a yaml file, you can use "[key]": value In application.yml file:
要从 yaml 文件提供 kafkaConsumer 配置,您可以使用 "[key]": value 在 application.yml 文件中:
kafkaConsumerConfig:
"[bootstrap.servers]": localhost:9092, localhost:9093, localhost:9094
"[group.id]": test-consumer-group-local
"[value.deserializer]": org.apache.kafka.common.serialization.StringDeserializer
"[key.deserializer]": org.apache.kafka.common.serialization.StringDeserializer
回答by liuxun
I had a simple code for Spring Cloud Config
我有一个简单的 Spring Cloud Config 代码
like this:
像这样:
In application.properties
在 application.properties 中
spring.data.mongodb.db1=mongodb://[email protected]
spring.data.mongodb.db2=mongodb://[email protected]
spring.data.mongodb.db1=mongodb://[email protected]
spring.data.mongodb.db2=mongodb://[email protected]
read
读
@Bean(name = "mongoConfig")
@ConfigurationProperties(prefix = "spring.data.mongodb")
public Map<String, Map<String, String>> mongoConfig() {
return new HashMap();
}
use
用
@Autowired
@Qualifier(value = "mongoConfig")
private Map<String, String> mongoConfig;
@Bean(name = "mongoTemplates")
public HashMap<String, MongoTemplate> mongoTemplateMap() throws UnknownHostException {
HashMap<String, MongoTemplate> mongoTemplates = new HashMap<>();
for (Map.Entry<String, String>> entry : mongoConfig.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
MongoTemplate template = new MongoTemplate(new SimpleMongoDbFactory(new MongoClientURI(v)));
mongoTemplates.put(k, template);
}
return mongoTemplates;
}
回答by wild_nothing
To get this working with YAML, do this:
要使其与 YAML 一起使用,请执行以下操作:
property-name: '{
key1: "value1",
key2: "value2"
}'
回答by ShareYourWisdom
Following worked for me:
以下为我工作:
SpingBoot 2.1.7.RELEASE
SpingBoot 2.1.7.RELEASE
YAML Property (Notice value sourrounded by single quotes)
YAML 属性(用单引号括起来的通知值)
property:
name: '{"key1": false, "key2": false, "key3": true}'
In Java/Kotlin annotate field with (Notice use of #) (For java no need to escape '$' with '\')
在 Java/Kotlin 中使用 (Notice use of #) 注释字段(对于 Java 不需要用 '\' 转义 '$')
@Value("#{${property.name}}")