Using @Value with condition in spring in order to map value to string
Asked Answered
D

2

9

I have a application.properites file with the following:

xxx.xxx = sandbox
xxx.sandbox = 123
xxx.production = 456

I would like to map to a string value 123 in case xxx.xxx == sandbox and 456 in case xxx.xxx == production

...
public class temp { 

 @Value("${??????}")
    private String token;
}

is it possible to fill in a condition incited of the ?????? that will map the token to 123 or 456 according to xxx.xxx ?

Disaccharide answered 10/5, 2016 at 15:57 Comment(1)
Use profiles instead, loading the appropriate property files for each.Bracing
D
19

A simple way in case someone will hit this question:

@Value("#{'${xxx.xxx}'=='sandbox' ? '${xxx.sandbox}' : '${xxx.production}'}")

I just think it is much easier that start working with profiles.

Disaccharide answered 14/5, 2016 at 16:54 Comment(1)
Aweswome! I was missing the quotes around the inner '${xxx.xxx}'Lenardlenci
J
4

You can use Spring Profiles, so you can have a property file for each enviroment.

Spring Profiles provide a way to segregate parts of your application configuration and make it only available in certain environments. Any @Component or @Configuration can be marked with @Profile to limit when it is loaded

You can see more here http://www.baeldung.com/spring-profiles

http://www.mkyong.com/spring/spring-profiles-example/

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

Josphinejoss answered 10/5, 2016 at 17:0 Comment(5)
after i'm using the above profile technic, how should i map the xxx.sandbox or xxx.production according to the profile from the application.properites file?Disaccharide
What kind of application are you running ? You can use this property -Dspring.profiles.active=production" at the moment you run the applicationJosphinejoss
OK, but these profile can help you to map the beans for spring, how i can use it to map in case of profile x use xxx.production, in case of profile y use xxx.sandbox?Disaccharide
You can use something like this <beans profile="dev"> <util:properties id="myproperties" location="WEB-INF/dev.properties" /> </beans> <beans profile="qa"> <util:properties id="myproperties" location="WEB-INF/qa.properties" /> </beans> at the end, thats depends on how are you reading the propertiesJosphinejoss
Thanks! it helps a lot!Disaccharide

© 2022 - 2024 — McMap. All rights reserved.