Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用Spring注入属性文件?_Java_Spring - Fatal编程技术网

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

Java 如何使用Spring注入属性文件?,java,spring,Java,Spring,如何使用spring将以下键值文件作为Properties变量或HashMap直接插入 src/main/resources/myfile.properties: key1=test someotherkey=asd (many other key-value pairs) 以下各项均无效: @Value("${apikeys}") private Properties keys; @Resource(name = "apikeys") private Properties keys; 旁

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

src/main/resources/myfile.properties:

key1=test
someotherkey=asd
(many other key-value pairs)
以下各项均无效:

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

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

旁注:我事先不知道属性文件中的键。因此,我不能使用
@PropertyResource
注入。

为了使用
注释,首先需要在bean下面的
应用程序上下文.xml
中定义

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

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

可以使用注释:

示例:

@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;
    }
}

您可以尝试通过在配置文件中创建bean来实现这一点:

@Bean
public Map<String, String> myFileProperties() {
    ResourceBundle bundle = ResourceBundle.getBundle("myfile");
    return bundle.keySet().stream()
            .collect(Collectors.toMap(key -> key, bundle::getString));
}
@Bean
公共映射myFileProperties(){
ResourceBundle=ResourceBundle.getBundle(“myfile”);
返回bundle.keySet().stream()
.collect(Collectors.toMap(key->key,bundle::getString));
}
然后您可以轻松地将这个bean注入到您的服务中

@Autowired
private Map<String, String> myFileProperties;
@Autowired
私有映射myFileProperties;
(考虑使用构造函数注入)

也别忘了


@PropertySource(“classpath:myfile.properties”)

您使用的是哪个spring版本?
spring boot.1.5.3
,因此,如果您希望像以前那样声明它,最新的
spring 4
不可能开箱即用(您需要一个单独的类来实现)。但是如果您可以像字符串
propertyMap={key1:test,key2:test2}
那样声明它,那么您可以使用SPEL直接映射到Map@membersound
@Value
是强制性要求吗?你会考虑使用<代码> @配置属性< /代码>吗?我可能更喜欢基于注释的配置,因为SRIPIG4不使用XML配置文件。哦,好的,抱歉没有注意到,而且在4.X之前仍然有用。不幸的是,这仅对静态值有用。membersound在回答属性文件中的键未知后添加了一个编辑。