【问题标题】:How to inject a Map using the @Value Spring Annotation?如何使用@Value Spring Annotation 注入 Map?
【发布时间】:2015-08-21 21:42:28
【问题描述】:

如何在 Spring 中使用 @Value 注释从属性文件中将值注入 Map?

我的 Spring Java 类是,我尝试使用 $,但收到以下错误消息:

无法自动装配字段:私有 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;

}

我在 .properties 文件中有以下属性

com.test.standard.name1=Pattern1
com.test.standard.name2=Pattern2
com.test.standard.name3=Pattern3
com.hello.foo.enabled=true

【问题讨论】:

  • 你需要使用spring表达式语言。使用列表(stackoverflow.com/questions/27390363/…)的类似问题。我不确定您是否可以开箱即用地做您想做的事情。这个问题stackoverflow.com/questions/28369458/… 更符合您的观点。使用自定义属性映射器
  • 您的地图到底想要什么?看来您还期望某种类型转换为Pattern?这是什么Pattern 类?
  • @Erlandsson 这是一个正则表达式模式,我们将在值中定义有效的正则表达式模式字符串
  • @LaurentuiL uin Spring boot,如果映射与类级别描述的前缀匹配,我可以直接注入映射,但是,我的问题是类级别的前缀并且此属性级别不同跨度>

标签: java spring dependency-injection annotations spring-annotations


【解决方案1】:

您可以像这样使用 @Value 注释从属性文件将值注入 Map。

属性文件中的属性。

propertyname={key1:'value1',key2:'value2',....}

在您的代码中。

@Value("#{${propertyname}}")  private Map<String,String> propertyname;

请注意标签作为注释的一部分。

【讨论】:

  • 如果属性不存在如何设置默认值以防止异常发生?
  • 似乎也进行类型转换,例如:@Value("#{${double.map}}") final Map&lt;String, Double&gt; doubleMap
  • 如何在 yml 文件中指定相同
  • @MukulAnand 在 yaml 中看起来像这样 propertyname : &gt; { key1:'value', key2:'value' } 抱歉,我无法正确格式化换行符
  • pattern "propertyname: {key1:'value1',key2:'value2',....}" 从 .yaml 注入地图时不起作用:java.lang.IllegalArgumentException:无法解析占位符
【解决方案2】:

我相信 Spring Boot 支持使用 @ConfigurationProperties 注解开箱即用地加载属性映射。

根据该文档,您可以加载属性:

my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com

像这样变成豆子:

@ConfigurationProperties(prefix="my")
public class Config {

    private List<String> servers = new ArrayList<String>();

    public List<String> getServers() {
        return this.servers;
    }
}

我之前使用过@ConfigurationProperties 功能,但没有加载到地图中。您需要使用@EnableConfigurationProperties annotation 来启用此功能。

这个功能很酷的地方在于你可以validate your properties

【讨论】:

  • 是的,但是,我的问题是.. Test 类有自己的 @ConfigurationProperties 前缀。所以我想单独为这个成员变量使用一个差异前缀。我该怎么做?
  • 嗯,我错过了。所以我会用 @ConfiguraitonProperties 注释创建单独的两个 bean 并将它们自动装配到测试类中。
  • 可能对 OP 有效,但问题没有指定启动,而且这个问题不适用于一般 Spring,没有启动。
  • 问题是如何使用 @Value 注释注入地图,但您是在告诉各种事情,而不是给出问题的答案。替代方案还可以,但也请坚持答案
【解决方案3】:

您可以使用@Resource 注解将.properties 作为映射注入到您的类中。

如果您使用的是 XML based configuration, 然后在您的 spring 配置文件中添加以下 bean:

 <bean id="myProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
      <property name="location" value="classpath:your.properties"/>
 </bean>

对于,基于注释:

@Bean(name = "myProperties")
public static PropertiesFactoryBean mapper() {
        PropertiesFactoryBean bean = new PropertiesFactoryBean();
        bean.setLocation(new ClassPathResource(
                "your.properties"));
        return bean;
}

然后您可以在您的应用程序中将它们作为地图选取:

@Resource(name = "myProperties")
private Map<String, String> myProperties;

【讨论】:

  • 我们使用 Spring Cloud Config 服务器来提供配置,因此类路径方法可能不起作用。而且我们不使用 XMLs
  • @Arpit - 你能在这里指导我吗:stackoverflow.com/questions/60899860/…
【解决方案4】:

我有一个简单的 Spring Cloud Config 代码

像这样:

在 application.properties 中

spring.data.mongodb.db1=mongodb://test@test1.com

spring.data.mongodb.db2=mongodb://test@test2.com

阅读

@Bean(name = "mongoConfig")
@ConfigurationProperties(prefix = "spring.data.mongodb")
public Map<String, Map<String, String>> mongoConfig() {
    return new HashMap();
}

使用

@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;
}

【讨论】:

  • 我认为您对 bean mongoConfig 的定义不正确。该方法应该这样定义。 public Map mongoConfig() { return new HashMap(); }
  • 如果您只是想从 application.yml 注入地图,这可能是最优雅的方式
【解决方案5】:

要使用 YAML,请执行以下操作:

property-name: '{
  key1: "value1",
  key2: "value2"
}'

【讨论】:

    【解决方案6】:

    这就是我们的做法。 两个示例类如下:

    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);
        }
    ...
    

    要从属性文件中提供 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
    

    要从 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
    

    【讨论】:

      【解决方案7】:

      以下对我有用:

      SpingBoot 2.1.7.RELEASE

      YAML 属性(注意值用单引号括起来)

      property:
         name: '{"key1": false, "key2": false, "key3": true}'
      

      在 Java/Kotlin 中用(注意使用#)注释字段(对于 java 不需要用 '\' 转义 '$')

      @Value("#{\${property.name}}")
      

      【讨论】:

      • 如果找不到属性,如何正确回退到空地图?否则上下文不会被初始化。
      猜你喜欢
      • 1970-01-01
      • 2014-09-15
      • 2013-01-15
      • 2011-09-19
      • 2011-11-17
      • 2018-03-16
      • 2019-03-29
      • 2019-05-01
      相关资源
      最近更新 更多