Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set null as the default value for a @Value in Spring?

I'm currently using the @Value Spring 3.1.x annotation like this:

@Value("${stuff.value:}")
private String value;

This puts an empty String into the variable if the attribute is not present. I would like to have null as the default instead of an empty String. Of course I also want to avoid an error when the property stuff.value is not set.

like image 361
Kevin Schmidt Avatar asked Oct 07 '22 17:10

Kevin Schmidt


People also ask

Can null be a default value?

If no default value is declared explicitly, the default value is the null value. This usually makes sense because a null value can be considered to represent unknown data. In a table definition, default values are listed after the column data type.

How do I set default value in spring?

To set a default value for primitive types such as boolean and int, we use the literal value: @Value("${some. key:true}") private boolean booleanWithDefaultValue; @Value("${some.

Can a request Param be null?

Method parameters annotated with @RequestParam are required by default. will correctly invoke the method. When the parameter isn't specified, the method parameter is bound to null.

Can we inject null and empty string values in spring beans?

In Spring dependency injection, we can inject null and empty values. In XML configuration, null value is injected using <null> element.


2 Answers

This is really old, but you can use Spring EL now, e.g.

@Value("${stuff.value:#{null}}")

See this question.

like image 169
ben3000 Avatar answered Oct 11 '22 09:10

ben3000


Thanks to @vorburger:

@Value("${email.protocol:#{null}}")
String protocol;

will set the string value at null without any other configurations.

like image 36
Kirill Ch Avatar answered Oct 11 '22 08:10

Kirill Ch