如何使用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
注射。
答案 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)