SpringBoot中@Value注解设置默认值

在SpringBoot项目读取配置文件中读取值,我们会用到@Value注解来读取配置值,例如我们在配置文件中配置了服务器web域名为xxx.com的配置:

server.web.domain=xxx.com

在代码中读取其配置项:

@Value("${server.web.domain}")
private String domain;

如果这个配置项在配置文件中忘记配置或者有的场景中我们不需要配置这项的时候,在项目启动的时候就会报错。
报错信息如下:

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'server.web.domain' in value "${server.web.domain}"
	at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178)
	at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124)
	at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239)
	at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210)
	at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:175)
	at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:918)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1248)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1227)
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119)
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
	... 18 common frames omitted

这个时候就需要我们给@Value注解配置项给个默认值。
解决方法如下:

 @Value("${server.web.domain:#{null}}")
 private String domain;

或者

 @Value("${server.web.domain:xxx}")
  private String domain;

不过如果默认值我们要设置为null时,我们使用${server.web.domain:null}时,拿到domain的默认值会是“null" null的字符串,所以这种情况下,我们使用 ${server.web.domain:#{null}} 这种方式进行赋予默认值

  • 14
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值