在Spring的框架中,我们经常使用@Value注解来获取定义在、、第三方Apollo/Nacos等等的属性值。
但是,有时候因为不小心写错了一些东西就导致取不到值,这里总结一下希望帮助有疑惑的小朋友们。
假如我们在properties配置了一个参数:
spring.test.city=beijing
使用时:
@Value("${}")
private String city;
以下情况会导致取不到值:
1. 最先需要确认的是没有写错
属性名太长,一定要去复制,别太自信总是手敲。
2. 使用static或者final修饰
一般没人这么用吧。
@Value("${}")
private final String city;// 取不到
final会报错:
Parameter 0 of constructor in com.properities.ProjectProperties required a bean of type '' that could not be found.
static的用法怪怪的,不要用。
3. 当前类未被Sprig管理
忘记加注解了,@Service、@Component之类。
@Component // 这里记得噢
@Data
public class ProjectProperties {
@Value("${}")
private String city;
}
4. 没有使用@Autowired直接new新建了实例
public class Test{
/*错误用法*/
ProjectProperties properties = new ProjectProperties ();
/*正确用法*/
@Autowired
ProjectProperties properties;
}
5. 使用默认值冒号前有空格
今天就栽在这里了╰(艹皿艹 )
// 千万不要加空格,最好前后都不要加
@Value("${ : beijing}") // 为了格式好看加了空格就取不到了
private String city;
在Spring
的@Value
注解中,冒号(:
)的作用是指定属性值的默认值。当获取属性值时,如果属性值不存在或为null
,则会使用冒号后面的默认值作为属性值。