Issue
I'm trying to set an Integer property to a default value of 1 if it either does not exist or if its current value is 0 and I can't for the life of me get the 0 comparison to work properly.
The original value (if set) will come in via the command line.
Here are the relevant line in my class:
@Configuration
public class AppConfig {
@Value("${${instance.procmultiplier} == 0 ? Integer.parseInt('1') : ${instance.procmultiplier}}")
public Integer procMultiplier;
}
I have tried numerous variations of the @Value annotation and at one point, I swear it recognized the 0 value, and I can't get back to that state. I was first trying to simply get it to recognize the 0 value and default to 1 and I was then going to try and insert a null-check.
Is there a way to do both all in the same annotation? One idea I had was to split the null-check and 0-check into two different properties, basically have procmultiplier=${instance.procmultiplier:1}
in a properties file and then change the annotation to @Value("${${procmultiplier} == 0 ? Integer.parseInt('1') : ${procmultiplier}}")
but nothing I try works.
My command is: mvn clean package && java -Dspring.profiles.active=json -Dinstance.procmultiplier=0 -jar target/MyApp-0.0.1-SNAPSHOT.jar
.
The property ends up just being equal to whatever I set it to on the command line.
Any ideas on how to check for both non-existent and 0 and default to 1 if either is true, otherwise set to whatever comes in via command line?
Solution
It appears my problem was using ${...}
instead of #{...}
. Here is my solution using two different properties:
bootstrap.properties
procmultiplier=${instance.procmultiplier:1}
AppConfig.java
@Configuration
public class AppConfig {
@Value("#{${procmultiplier} == 0 ? 1 : ${procmultiplier}}")
public Integer procMultiplier;
}
Command Line:
mvn clean package && java -Dspring.profiles.active=json -Dinstance.procmultiplier=0 -jar target/MyApp-0.0.1-SNAPSHOT.jar
Also allows for a missing instance.procmultiplier
parameter.
I still don't know how to do it all in one shot with 1 property though...
Answered By - Brooks
Answer Checked By - Clifford M. (JavaFixing Volunteer)