如何使用Spring注入属性文件?

时间:2017-05-16 08:17:49

标签: java spring

如何使用Properties直接将以下键值文件作为HashMap变量或spring注入?

的src /主/资源/ myfile.properties:

key1=test
someotherkey=asd
(many other key-value pairs)

以下任何一项均无效:

@Value("${apikeys}")
private Properties keys;

@Resource(name = "apikeys")
private Properties keys;

旁注:我事先并不知道属性文件中的键。所以我不能使用@PropertyResource注射。

3 个答案:

答案 0 :(得分:2)

为了首先使用Value注释,您需要在applicationContext.xml下面的bean中定义

<bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:myfile.properties"></property>
</bean> 

定义属性文件后,可以使用Value注释。

答案 1 :(得分:1)

One way you could try to achieve this is by creating a bean in your configuration file:

@Bean
public Map<String, String> myFileProperties() {
    ResourceBundle bundle = ResourceBundle.getBundle("myfile");
    return bundle.keySet().stream()
            .collect(Collectors.toMap(key -> key, bundle::getString));
}

Then you can easily inject this bean into your service e.g.

@Autowired
private Map<String, String> myFileProperties;

(Consider using constructor injection)

Also don't forget to

@PropertySource("classpath:myfile.properties")

答案 2 :(得分:0)

您可以使用注释PropertySource

<强>示例:

UIImage.imageOrientation