How to read Map value from application.properties file using Environment API - java

I have application.properties file which contains Map values like below,
myMap={key1:'value1',key2:'value2',....}
Now I know I can read this using,
#Value("#{${myMap}}")
private Map<String,String> myMap;
But I want to read this using Environment API. But I don't see proper method to fetch the Map value as Map. All I see is
import org.springframework.core.env.Environment;
#Autowired
private Environment env;
Map<String,String> myMap = env.getProperty("myMap"); // returns String
How can I get a Map directly from the properties file using the Enviromnet API? Or I need to do conversions on my own?
Any help is appreciated.

Related

Spring #Value annotation with List and default value

I have a property in config file, which contains a list of values in such format. The format has to remain the same.
myapp.values=value1,value2,value2
I use these values in my config class like that:
#Value("#{'{myapp.values}'.split(,)}")
private List<String> values;
My question is there a way to make a default value (empty list or null) it there is no such property in config file or the property is empty?
I tried to google this with no success. People either use myapp.values={value1,value2,value3} which doesn't suit me or format for that or use default values for simple variables, not lists.
My question is only about achieving the goal by changing the #Value annotation. Pls do not suggest workarounds
#Value("${myapp.values:}#{T(java.util.Collections).emptyList()}")
private List<String> defaultToEmpty;
or
#Value("#{T(java.util.Arrays).asList('${myapp.values:}')}")
private List<String> defaultToEmpty = new ArrayList();
Actually, just one symbol : with an empty default value will work:
#Value("${myapp.values:}")
private List<String> values;

Injecting values into Hashmap using java Spring

I was able to use java Spring annotation to inject key values pair into the hashmap as follows
validationError.properties file
errorcode.map={\
"default.labOrder.oneservice": "AAAAAA", \
"default.labOrder.patient.firstName": "BBBBB", \
}
I able to use the following code to inject the values into my hashmap as follows
#Value("#{${errorcode.map}}")
private Map<String, String> errorNumberMap;
However if I have a property file with the following values
errorcode.map={\
"LAB": "AAAAAA, BBBB, CCCC", \
"ECP": "AAAAAA, BBBB, CCCC", \
}
and a map Hashmap<AccessType, List> preserveMap = new HashMap() where AccessType is an enum. Does spring has any annotation that will populate my preserveMap value?
Thanks!
Mapping properties directly into bean fields only support simple basic mappings between properties and field values.
Using a configuration object gives more options and can do this kind of tricks and is also more readable.
https://www.baeldung.com/configuration-properties-in-spring-boot

How to get the map values from "yml" file as a Map?

I have a "details.yml" file, considering all the setting for getting all values from "yml.file" is done. But I am unable to store Map values into
"Map"
Here is my "details.yml" file below
details:
company:XYZ
values:
name: Manish
last: Raut
And in my class file i am able to get the values of "company" from yml file using #Value("${company}")
#Component
#EnableConfigurationProperties
#ConfigurationProperties(prefix = "details")
public class abcd() {
#Value("${company}")
String company;
#Value("${values}")
Map<String, String> values =new HashMap<String, String>();
...............................
}
i am not able to get those values in Mao which i created in this class, but i am getting values for "Company".
Help me with this?
Im the past, I added getter/setter for MAP type and it was work.
Did you try it? (getter/setter for 'values')
I'm not really sure what marshalling framework Spring uses behind the scenes and how it configures it (you could probably find out with some debugging and maybe make it work for your case), but you could always add an extra layer to your application and configure your own.
For instance you could use Jackson with yaml dataformat - https://dzone.com/articles/read-yaml-in-java-with-jackson.

Populating a HashMap with entries from a properties file for #Value

I have properties file which has a key company.id like this
company.id=key1=value1,key2=value2,key3=value4
Now, I want to store key-value pair directly in map using #Value of spring
//For example,
//for key in properties file
//company.list=comp1,comp2
#Value("#{'${proposal.provience}'.split(',')}")
List<String> companyList;
the above will directly converts to List.
Please tell me what to write here without using other libraries like Guava
#value(some logic here)
HashMap<String,String> map;

How to load nested key value pairs from a properties file in SpringBoot

Is there a better manner to implement properties file having key-value pairs as value using Spring/Spring Boot?
I want to create a property file where the key contains a couple of key-value pair as value.
I tried below implementation:-
Properties file:-
Fiat=model:pet,year:1996
Honda=model:dis,year:2000
And i have below class trying to read the properties file.
#Component
#PropertySources(#PropertySource("classpath:sample.properties"))
public class PropertiesExtractor {
#Autowired
private Environment env;
public String pullValue(String node) {
String value = env.getProperty(node);
System.out.println(value);//for Fiat, i get syso as **model:pet,year:1996**
}
}
I need to parse the values using java, to get the individual value. Is this the only way out to implement this.
Is there a better way to use nested property files in Java?
Create a Car object or something with a model and a year property. Then create something like this
#ConfigurationProperties("foo")
public class CarProperties {
private Map<String,Car> cars;
// Getters/Setters
}
Add add #EnableConfigurationProperties(CarProperties.class) in your main configuration class.
Then you can inject that config as follows:
foo.cars.Fiat.model=pet
foo.cars.Fiat.year=1996
foo.cars.Honda.model=dis
foo.cars.Honda.year=2000
There is more info in the doc.
You can use yaml files with spring as well:
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-yaml
This way, you can work with
Fiat:
model: pet
year: 1996
Honda:
model: dis
year: 2000

Categories

Resources