我可以在Spring中将null设置为@Value的默认值吗?

Kev*_*idt 83 java spring spring-annotations

我目前正在使用@Value Spring 3.1.x注释,如下所示:

@Value("${stuff.value:}")
private String value;
Run Code Online (Sandbox Code Playgroud)

如果属性不存在,这会将空字符串放入变量中.我想将null作为默认值而不是空字符串.当然,我还想避免在未设置属性stuff.value时出错.

ben*_*000 154

这真的很旧,但你现在可以使用Spring EL,例如

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

看到这个问题.

  • 应选择此作为问题的答案。 (3认同)

小智 60

您必须设置PropertyPlaceholderConfigurer的nullValue .对于示例,我使用的是字符串,@null但您也可以将空字符串用作nullValue.

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <!-- config the location(s) of the properties file(s) here -->
    <property name="nullValue" value="@null" />
</bean>
Run Code Online (Sandbox Code Playgroud)

现在您可以使用该字符串@null来表示该null

@Value("${stuff.value:@null}")
private String value;
Run Code Online (Sandbox Code Playgroud)

请注意:上下文名称空间目前不支持空值.你不能使用

<context:property-placeholder null-value="@null" ... />
Run Code Online (Sandbox Code Playgroud)

用Spring 3.1.1测试

  • http://stackoverflow.com/questions/9347929/spring-set-a-property-only-if-the-value-is-not-null使用$ {some.param:#{null}}提及,这是有效的对我而言,无需设置nullValue,似乎这是默认值?(在Spring Boot应用程序中.) (28认同)
  • 根据vorburger和http://stackoverflow.com/questions/16735141/specify-default-property-value-as-null-in-spring的建议,简单使用SPEL $ {stuff.value:#{null}} (5认同)
  • 什么是Java配置相当于此? (2认同)

Kir*_* Ch 28

感谢@vorburger:

@Value("${email.protocol:#{null}}")
String protocol;
Run Code Online (Sandbox Code Playgroud)

将字符串值设置为null而不进行任何其他配置.

  • 在 spring-boot 2019 年最后一个版本中工作:2.1.7.RELEASE ... https://start.spring.io/ (3认同)