springboot自定义属性获取不到,在浏览器中获取为{},控制台显示com.ysj.entity.Product@5f2daae1怎么回事?

图片说明
图片说明图片说明图片说明

1、@PropertySource 不支持yml文件。只支持.properties文件

你如果需要读取yml文件可以自己写一个解析器

public class YmlconfigFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        // 获取配置文件名称
        String sourceName = name != null ? name : resource.getResource().getFilename();
        // 判断是否存在
        if (!resource.getResource().exists()) {
            // 创建空的资源
            return new PropertiesPropertySource(sourceName, new Properties());
        } else
            // 判断是不是yml文件
            if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
            // 是yml文件
            return new PropertiesPropertySource(sourceName, loadYml(resource));
        } else {
            // 不是yml文件调用父类方法
            return super.createPropertySource(name, resource);
        }
    }

    /**
     * 读取yml文件
     * */
    private Properties loadYml(EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}

==使用==

@Component
@PropertySource(value = {"classpath:a.yml"}, factory = YmlconfigFactory.class)
@ConfigurationProperties(prefix = "product")
public class testCache {

    private String name;
    private String password;
    private String sex;

    @Override
    public String toString() {
        return "testCache{" +
                "name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

==调用==

```java
public void test(){
    System.out.println(testCache.toString());
}

```
        ==结果==

图片说明

2、你的yml文件格式也要注意一下
图片说明

product:
  name: Tom
  password: admin
  sex: 男

https://blog.csdn.net/yusimiao/article/details/97622666?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task