springboot 中使用@Value 获取配置文件中参数问题

springboot 中使用
@Value("${spring.redis.password}")

获取配置文件中参数时 ,如果配置文件中没有相关参数,项目启动时会报错

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.redis.password' in value "${spring.redis.password}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:180)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
    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)

 

解决方法

使用

@Value("${spring.redis.password:}")  如果没有password参数 则为:后的值  这里为空字符串


@Value("${name:codeMcDull}")
private String name;



@Value("${age:18}")
private String age;

 

posted @ 2023-03-14 10:23  mcdullcode  阅读(778)  评论(0)    收藏  举报