![](/img/trans.png)
[英]Spring Boot injecting Map values from .properties and .yaml using ConfigurationProperties
[英]Spring Boot: read list of objects from yaml using @ConfigurationProperties is always returning null
我想创建一个 yaml 文件,从中获取常量
常量配置.yml
constants:
myList:
-
id: 11
name: foo1
firstName: bar1
allowed: true
-
id: 22
name: foo2
firstName: bar2
allowed: false
配置类如下所示:
@Data
@Component
@PropertySource("classpath:constantsConfiguration.yml")
@ConfigurationProperties(prefix = "constants")
public class ConstantProperties {
private List<User> myList;
@Data
public static class User{
private String id;
private String name;
private String firstName;
private Boolean allowed;
}
}
这是我想如何使用它的一个虚拟示例
@Service
@RequiredArgsConstructor
public class MyService{
private final ConstantProperties constantProperties;
public Boolean isEmptyList(){
return CollectionUtils.isEmpty(constantProperties.getMyList());
}
}
constantProperties.getMyList()
始终为 null 我正在使用 spring boot:2.5.12 和 java 11
根本原因是新的SpringBoot不会将properties文件解析为yaml properties。
您需要先添加一个 Yaml PropertiesSourceFactory 类。 如下所示:
import java.io.IOException;
import java.util.Properties;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(encodedResource.getResource());
Properties properties = factory.getObject();
return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
}
}
然后在:ConstantsProperties 类中,需要明确指定Factory 类。 喜欢:
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import lombok.Data;
@Data
@Component
@PropertySource(value = "classpath:constantsConfiguration.yml", factory = YamlPropertySourceFactory.class)
@ConfigurationProperties(prefix = "constants")
public class ConstantProperties {
private List<User> myList;
@Data
public static class User {
private String id;
private String name;
private String firstName;
private Boolean allowed;
}
}
最后,请注意您的 yaml 文件格式。 每个分隔符应该是 2 ' ' 空白字符。
请尝试一下,它现在应该可以工作了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.