Reputation: 1
Is it possible to use @Value annotation with a variable as default?
I have a variable processingYear
, I would like to read from properties, If it cannot read from properties, I would like to assign the current year into the variable.
@Value("${processing_year:2021}")
int processingYear;
With the code specific above, I can read the processingYear
from the properties file, and assign value to it, if reading from properties failed, the variable will be set to 2021.
However, I do not see a way to assign the current year as a default variable currentYear
. Following is what I imagined and would like to see if there is anything to assign a default variable to it.
LocalDate date = LocalDate.now();
Locale locale = Locale.US;
int currentYear = Integer.parseInt(date.format(DateTimeFormatter.ofPattern("yyyy",locale)));
@Value("${process_year:currentYear}")
int processingYear;
Upvotes: 0
Views: 2462
Reputation: 950
Well you can do it with @Value
Just try this:
@Value("${currentYear:#{(T(java.time.Year).now().getValue())}}")
private int year;
Upvotes: 1
Reputation: 4935
Yes you can provide as below :
@Value("${processing_year:5}")
int processingYear;
Provide the default value after :
. This would assign a default value of 5
to processingYear
If you want to provide other values then you need to prefix with #
:
@Value("$someObj.value:#{null}}")
Object someObj;
@Value("#{'${someObject.stringlist:}'.split(',')}")
Collection<String> strings;
If you need to set a variable, then you need to use @Value
along with a setter method:
int processingYear;
@Value("${process_year:-1}")
private void setProcessingYear(int year) {
if(year == -1) {
// -1 used to identify that no value was passed. so in this case we use currentyear.
year = currentyear;
}
processingYear = year;
}
Upvotes: 0