Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 979
USer22999299 Avatar asked May 10 '16 15:05

USer22999299


People also ask

What is the use of @value annotation in spring?

Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. Spring @Value annotation also supports SpEL.

Can we use @value inside a method?

no :) you can use annotations to annotate classes, fields, methods and their arguments. but not in methods, since there is no way, to get method- local variables using reflection in order to process these annotations. Use @Value in your field, and read the value from your method.

How do you inject a map from a Yaml file in spring boot?

How to Inject a Map From a YAML File. Spring Boot has taken data externalization to the next level by providing a handy annotation called @ConfigurationProperties. This annotation is introduced to easily inject external properties from configuration files directly into Java objects.


1 Answers

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.

like image 75
USer22999299 Avatar answered Oct 25 '22 20:10

USer22999299