I have my colour.roperties file as
rose = red
lily = white
jasmine = pink
I need to get the value for colour as
String flower = runTimeFlower;
@Value("${flower}) String colour;
where flower value we will get at runtime. How can I do this in java Spring. I need to get a single value (from among 50 values defined in the properties file )at runtime based on the user input. If i cannot use @Value , Could you tell me other ways to handle this please?
You can use @Value("${property-name}") from the application. properties if your class is annotated with @Configuration or @Component . You can make use of static method to get the value of the key passed as the parameter. Save this answer.
Get All Key Values from Properties File Get All Key Values from Properties File in java using the Properties class Available in java. util Package. The Properties class extends the Hashtable class. From Hashtable, Properties class inherits the Method KeySet() which Returns a Set view of the keys Contained in this Map.
There is no way to do what you are describing using @Value, but you can do this, which is the same thing pretty much:
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 + "}");
}
}
The PropertySource
s which Spring reads from won't know the value of the flower
variable, so @Value
won't work.
Inject a Properties
object or a Map
. Then just look up the colour using the property name or key, respectively, e.g.
<util:properties id="appProperties" location="classpath:app.properties" />
...
@Autowired
@Qualifier("appProperties")
private Properties appProperties;
...
appProperties.getProperty(flower);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With