yuvraj
yuvraj

Reputation: 139

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.

Upvotes: 4

Views: 20303

Answers (3)

Armin Norozian
Armin Norozian

Reputation: 61

You can use @Value like this:

public class Student {
  @Value("${some.key:10}")
  private LookupDTO emp;
  private int totalMark;
  private string sub;
}

Upvotes: 0

Mehtrick
Mehtrick

Reputation: 526

How about this:

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

See this for further reference.

Upvotes: 1

Januson
Januson

Reputation: 4841

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.

Upvotes: 4

Related Questions