如何解决Springboot @ConfigurationProperties未注入
我无法让我的属性文件(export-fields.yml)注入地图。我已经在resources文件夹中创建了属性文件,链接到属性源,为属性对象创建了配置,并使用lombok生成了getter和setter,但仍然没有将任何内容填充到字段映射中(fields = null)。有什么我想念的吗?这是我到目前为止的代码
FieldReplacerProperties.java
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "export")
@PropertySource("classpath:export-fields.yml")
public class FieldReplacerProperties {
private Map<String,String> fields;
public List<String> columnsToFields(List<String> columns){
columns.parallelStream().forEach(column -> fields.get(column));
return columns;
}
}
FieldReplacerConfiguration.java
@Getter
@Setter
@Configuration
@EnableConfigurationProperties(FieldReplacerProperties.class)
public class FieldReplacerConfiguration {
@Autowired
private FieldReplacerProperties fieldReplacerProperties;
public List<String> columnsToFields(List<String> columns){
return fieldReplacerProperties.columnsToFields(columns);
}
}
export-fields.yml
export:
fields:
id: number
name: programName
type: contractType
term: contractTerm
...
我如何访问它
@Autowired
private FieldReplacerConfiguration fieldReplacerConfiguration;
//replace columns with fields
fieldReplacerConfiguration.columnsToFields(columns);
解决方法
Spring从application.properties(或yml)加载属性。尝试将属性从export-fields.yml移到application.yml
,添加了PropertySourceFactory并解决了该问题。
@PropertySource更改
@PropertySource(value = "classpath:export-fields.yml",factory = YamlPropertySourceFactory.class)
YML工厂
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name,EncodedResource encodedResource) {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(encodedResource.getResource());
Properties properties = factory.getObject();
return new PropertiesPropertySource(encodedResource.getResource().getFilename(),properties);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。