Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any option to set Default value using @Value in java spring properties?

I am working with Spring to assign a default value for a DTO property using @Value. I have two DTO classes:

public class Student {
  @Value("10") // default value of id should be "10"
  private LookupDTO emp;
  private int totalMark;
  private string sub;
}

public class lookUpDTO {
  private String id;
  private String name;
}

How do I assign a default value for id as 10 using @Value?

Note: lookUpDTO is used by other DTO also, so I cannot use @Value in lookUpDTO directly.

Thanks in advance.

like image 374
yuvraj Avatar asked Sep 14 '25 09:09

yuvraj


1 Answers

If the id property is in fact a value, then yes. You can tell Spring to inject this value or use default.

@Value("${some.key:my default value}")
private String id;

However, since you want just the default value and not to inject a value, @Value annotation is not what you want. Instead you could initialize the id in LookupDTO and Spring will replace it with incoming value.

public class LookupDTO {
    private String id = "10";
    private String name;

    // get, set, etc...
}

If this default value conflicts with other usages you will have to duplicate the class or handle the default value when you read it.

like image 188
Januson Avatar answered Sep 15 '25 23:09

Januson