简体   繁体   English

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

[英]How to inject a properties file using Spring?

How can I inject the following key-value file as a Properties variable or HashMap directly, using spring ? 如何使用spring将以下键值文件作为Properties变量或HashMap直接注入?

src/main/resources/myfile.properties: SRC /主/资源/ myfile.properties:

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

None of the following worked: 以下都不起作用:

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

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

Sidenote: I don't know the keys inside the properties file in advance. 旁注:我事先并不知道属性文件中的键。 So I cannot use @PropertyResource injection. 所以我不能使用@PropertyResource注入。

One way you could try to achieve this is by creating a bean in your configuration file: 您可以尝试实现此目的的一种方法是在配置文件中创建一个bean:

@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 eg 然后,您可以轻松地将此bean注入您的服务,例如

@Autowired
private Map<String, String> myFileProperties;

(Consider using constructor injection) (考虑使用构造函数注入)

Also don't forget to 也别忘了

@PropertySource("classpath:myfile.properties")

In order to use Value annotation first you need to define in your applicationContext.xml below bean 为了首先使用Value注释,您需要在bean下面的applicationContext.xml中定义

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

Once you define your property file , you can use Value annotation. 定义属性文件后,可以使用Value注释。

You can use Annotation PropertySource : 您可以使用Annotation PropertySource

Sample: 样品:

@PropertySource("myfile.properties")
public class Config {

    @Autowired
    private Environment env;

    @Bean
    ApplicationProperties appProperties() {
        ApplicationProperties bean = new ApplicationProperties();
        bean.setKey1(environment.getProperty("key1"));
        bean.setsomeotherkey(environment.getProperty("someotherkey"));
        return bean;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM