如何使用Spring 4注入键值映射?

时间:2016-04-06 09:11:39

标签: java spring spring-4

VI=Visa
MC=Mastercard
...

我可以使用Map<String, String>自动将其注入Spring吗?

像:

@Resource("${myfile.properties}")
private Map<String, String> creditcards;

这可能吗?

2 个答案:

答案 0 :(得分:2)

找到一个不错的功能:

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

将其注入任何地方,如下所示:

@Resource(name = "credit")
private Properties credit;

答案 1 :(得分:0)

你看到了这个: How to inject a Map using the @Value Spring Annotation?

在问题中,此人使用地图。那么也许你可以使用它?否则,您可以使用Properties类(https://docs.oracle.com/javase/7/docs/api/java/util/Properties.html),如果您确实需要地图,可以将properties-object转换为地图