在运行时根据输入java Spring从属性文件获取值
我的color.roperties文件是在运行时根据输入java Spring从属性文件获取值,java,spring,properties-file,Java,Spring,Properties File,我的color.roperties文件是 rose = red lily = white jasmine = pink 我需要得到颜色的值 String flower = runTimeFlower; @Value("${flower}) String colour; 我们将在运行时获得的花值。我如何在JavaSpring中做到这一点。我需要在运行时根据用户输入获取单个值(从属性文件中定义的50个值中选择)。如果我不能使用@Value,您能告诉我其他处理方法吗?使用@Value无法实现您所描
rose = red
lily = white
jasmine = pink
我需要得到颜色的值
String flower = runTimeFlower;
@Value("${flower}) String colour;
我们将在运行时获得的花值。我如何在JavaSpring中做到这一点。我需要在运行时根据用户输入获取单个值(从属性文件中定义的50个值中选择)。如果我不能使用@Value,您能告诉我其他处理方法吗?使用@Value无法实现您所描述的功能,但您可以做到这一点,这基本上是一样的:
package com.acme.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class Example {
private @Autowired Environment environment;
public String getFlowerColor(String runTimeFlower) {
return environment.resolvePlaceholders("${" + runTimeFlower + "}");
}
}
Spring从中读取的
PropertySource
s将不知道flower
变量的值,因此@value
将不起作用
插入属性
对象或映射
。然后分别使用属性名称或键查找颜色,例如
<util:properties id="appProperties" location="classpath:app.properties" />
...
@Autowired
@Qualifier("appProperties")
private Properties appProperties;
...
appProperties.getProperty(flower);
...
@自动连线
@限定符(“appProperties”)
私人物业;
...
appProperties.getProperty(flower);
什么@ike_love说的没错,但为什么不在应用程序启动时将属性加载到内存中,然后从地图上解析取花值呢?在我看来,你不需要把每一件像这样简单的事情都委托给Spring。无论如何,我不知道您的Spring配置,但是为了让Spring能够加载属性,您需要定义一个PropertyPlaceHolderConfigure来告诉属性文件在哪里:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:app.properties</value>
</list>
</property>
</bean>
类路径:app.properties
Upvoting是一个有效的选项,尽管我在回答中试图避免与Spring的紧密绑定。我想@user3147038还需要学会投票和接受答案