如何在 Spring Boot 的 application.yml 中定义默认空值 [英] How to define default null value in application.yml in Spring Boot

查看:73
本文介绍了如何在 Spring Boot 的 application.yml 中定义默认空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 SpringBoot 版本 1.3.0.RELEASE 在 application.yml 中将默认值定义为空值.目标是能够使用带有 ConfigurationProperties 注释的类来引用它

I'm trying to define the default value as null value in application.yml with SpringBoot version 1.3.0.RELEASE. The goal is be able to refer it with a class with ConfigurationProperties annotation

-- application.yml --
test.foo: ${test.bar:#{null}}

但它不起作用.

如果test.bar的值没有定义,设置test.foo为null(默认值)

If the value of test.bar is not defined, set test.foo to null (default value)

我的依赖项中已经有了 spring-el.我不想使用 PropertyPlaceholderConfigurer.setNullValue

I already have spring-el in my dependencies. I don't want to use PropertyPlaceholderConfigurer.setNullValue

它似乎在 @Value 中有效,但在 application.yml 中无效(请参阅 http://farenda.com/spring/spring-inject-null-value/)

It's seem to work in @Value but not in application.yml (see http://farenda.com/spring/spring-inject-null-value/)

这是一个错误,或者 yaml 不是为此而设计的?我尝试了 http://yaml.org/type/null.html 中的所有值,但它没有也没有用

It's a bug, or yaml is not designed for that? I tried all values in http://yaml.org/type/null.html but it doesn't worked either

谢谢

推荐答案

@Value

从文档中我们可以看出:

@Value

From the document, we can see:

一个常见的用例是使用#{systemProperties.myProp}"样式表达式分配默认字段值.

A common use case is to assign default field values using "#{systemProperties.myProp}" style expressions.

这里其实是三个阶段:

  • Spring获取注解字符串——AutowiredAnnotationBeanPostProcessor
  • Spring通过注解元数据获取属性值——Environmen
  • Spring解释属性值——ExpressionParser

如果我们像你描述的那样在 application.yml 中定义一个 test.foo:

If we define a test.foo in application.yml like you have described:

-- application.yml --
test.foo: ${test.bar:#{null}}

然后,我们通过@Value在代码中引用它,就如你所说.

Then, we refer to it in code via @Value, it works as you said.

@Autowired
public A(@Value("test.foo") Object a) {}

但是如果我们直接从 environment 获取它,它将是纯字符串:

But If we get it directly from environment, it will be plain string:

env.getProperty("test.foo")

更多

所以,它是否有效取决于您如何使用它.在获得更多信息之前,我无法提供更多帮助.希望关注相关帖子可能会有所帮助.

More

So, whether it is work or not depends on how did you use it. I can't provide more help before more info. Hope following related post may help.

这篇关于如何在 Spring Boot 的 application.yml 中定义默认空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆