idea中创建springboot中用@Value读取.yml文件无法读取里面的数据

   studenting:
     id:1
     name:liuyupeng

这个是application.yaml文件中的数据

然后测试

package com;

import com.domain.Student;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class Ch1101SpringbootApplicationTests {

	@Autowired
	private Student student;
	@Test
	void contextLoads() {
		System.out.println(student);
	}

}

结果报错

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'student': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'studenting.name' in value "${studenting.name}"

我的yaml文件都是有叶子图标的
 

你这个yaml配置好像有点问题吧,要严格按照yaml的语法了,这是个将空格用到极致的语法。

试下:注意冒号后面的空格

studenting:

id: 1

name: liuyupeng

@Component

public class Student {

    @Value("${studenting.id}")
    private int id;
    @Value("${studenting.name}")

}

.yaml文件中

studenting:
  id:1
  name:lg

就这么一眼过去 没有get set方法  也没有Lombok的注解 - -

使用@value注解

试试这样写@Value(value = "${studenting.id}")

studenting是不是顶层的?看你复制过来的   studenting前面还有缩进

@Value("${web.upload-path}")
private String uploadFoldName;

你的是

@Value("${studenting.name}")

private String studentingName;

这样就可以取到

但是记住 studenting靠近前面

加上@RunWith和对应的SpringBoot启动文件试下。

yml配置文件前面空格问题,

如下完整代码,供参考


创建Student

@Component //利用springIOC创建对象
public class Student {

    @Value("${studenting.id}")//将yml中的值通过set方法复值给属性id
    private String id;
    @Value("${studenting.name}")//将yml中的值通过set方法复值给属性name
    private String name;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    /**
     * 方便输出
     * @return
     */
    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

 

配置yml内容

 

studenting:
  id: 1
  name: liuyupeng


测试,注意需要创建spring测试换,应为设计springIOC内容和自动注入
@SpringBootTest
@RunWith(SpringRunner.class)//创建spring的测试环境
public class Ch1101SpringbootApplicationTests {

    @Autowired
    private Student student;
    @Test
    public void contextLoads(){
        System.out.println(student);
    }
}

 

测试结果