首页 > 解决方案 > Spring Boot JSON 配置返回 null

问题描述

我想将此 JSON 添加为我的 Spring 引导项目的外部配置:

{
    "napas":[
        {
            "bankId":1,
            "name":"abc",
            "napasName":"xyz",
            "napasId":"111"
        },
        {
            "bankId":2,
            "name":"mnk",
            "napasName":"tcb",
            "napasId":"2222"
        },
        {
            "bankId":3,
            "name":"qwer",
            "napasName":"tyu",
            "napasId":"888"
        }
    ]
}

这是我的配置类:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Configuration
@PropertySource(value = "classpath:napas-config.json", factory = JsonPropertySourceFactory.class)
public class NapasConfig {
    private List<Napas> napas;
}

这是我的目标:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Napas {
    private String bankId;
    private String name;
    private String napasName;
    private String napasId;
}

当然,有一个用于绑定的 Json 属性源工厂,我认为错误来自这里,但我不确定如何修复它:

public class JsonPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
        Map readValue = new ObjectMapper().readValue(encodedResource.getInputStream(), Map.class);
        return new MapPropertySource(encodedResource.getResource().getFilename(), readValue);
    }
}

当我注入NapasConfig我的服务并调用getNapas()列表时,它返回 null!有人可以解释为什么以及如何解决这个问题!

标签: springspring-boot

解决方案


@ConfigurationProperties您错过了使您的类成为配置属性类的重要注释

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Configuration
// This was missing
@ConfigurationProperties(prefix = "")
//
@PropertySource(value = "classpath:napas-config.json", factory = JsonPropertySourceFactory.class)
public class NapasConfig {
    private List<Napas> napas;
}

推荐阅读