如何使用 @Value Spring Annotation 注入 Map? [英] How to inject a Map using the @Value Spring Annotation?

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

问题描述

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

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

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

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

无法自动装配字段:private java.util.Map Test.standard;嵌套异常是 java.lang.IllegalArgumentException:无法解析字符串值${com.test.standard}"中的占位符com.test.standard"

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;

}

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

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

推荐答案

我相信 Spring Boot 支持使用 @ConfigurationProperties 注释.

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

像这样变成bean:

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

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

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

我之前使用过@ConfigurationProperties 功能,但没有加载到地图中.您需要使用 @EnableConfigurationProperties 注释 以启用此功能.

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 Spring Annotation 注入 Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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