在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}} 这种方式进行赋予默认值