如何注入使用@Value春天注解的地图? [英] How to inject a Map using the @Value Spring Annotation?

查看:183
本文介绍了如何注入使用@Value春天注解的地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用文件春季@Value注解注入到值从属性的Map?

我的Spring Java类是和我尝试使用$,但有以下错误消息


  

无法自动装配领域:私人的java.util.Map Test.standard;嵌套的例外是java.lang.IllegalArgumentException异常:无法解析占位符com.test.standard的字符串值$ {} com.test.standard


  @ConfigurationProperty(com.hello.foo)
公共类的测试{   @Value($ {com.test.standard})
   私人地图<弦乐,拼花>标准=新的LinkedHashMap<弦乐,拼花>   启用私人字符串;}

我在.properties下面的属性文件

  com.test.standard.name1 =样式1
com.test.standard.name2 =模式2
com.test.standard.name3 = Pattern3
com.hello.foo.enabled =真


解决方案

我相信春天引导支持加载的属性映射开箱与<一个href=\"http://docs.spring.io/spring-boot/docs/1.2.3.RELEASE/reference/htmlsingle/#boot-features-external-config-loading-yaml\"相对=nofollow> @ ConfigurationProperties 注释。

据该文档可以加载性能:

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

到像这个bean:

  @ConfigurationProperties(preFIX =我的)
公共类配置{    私人列表&LT;串GT;服务器=新的ArrayList&LT;串GT;();    公开名单&LT;串GT; getServers(){
        返回this.servers;
    }
}

我用@ConfigurationProperties之前功能,但没有加载到地图。你需要使用<一个href=\"http://docs.spring.io/spring-boot/docs/1.2.3.RELEASE/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties\"相对=nofollow> @ EnableConfigurationProperties注释以启用此功能。

有关此功能的酷的东西是,你可以验证性能

How can i inject values into a Map from the properties file using the @Value annotation in Spring ?

My Spring Java class is and i tried using the $ but, got the following error message

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}"

@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

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

解决方案

I believe Spring Boot supports loading properties maps out of the box with @ConfigurationProperties annotation.

According that docs you can load properties:

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

into bean like this:

@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 annotation to enable this feature.

Cool stuff about this feature is that you can validate your properties.

这篇关于如何注入使用@Value春天注解的地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆