SpringBoot中用@Value读取yml中的值报错

SpringBoot中用@Value读取yml中的值:

图片说明

读取:

图片说明

报错:Could not resolve placeholder 'spring.datasource.url' in value "${spring.datasource.url}"

为什么呢?我知道可以用@ConfigurationProperties去读取,但是为什么用@Value去获取就获取不到报错?

1、如果有多个yml文件时,确认下application.yml加载的是哪个yml
2、使用@Value的类是否被加载到spring容器中,若没有的话就要给类加上@Contorller/@Service/@Component/@Configuration之类的
3、最后再瞅一眼你的主启动类,是否添加了扫描yml的注解(@ComponentScan)

希望能对你的问题有所帮助。

是因为还没把yml文件加载进来吗