Springboot @ConfigurationProperties未注入

时间:2020-11-04 23:32:53

标签: java spring-boot properties configuration

我无法让我的属性文件(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);

2 个答案:

答案 0 :(得分:0)

Spring从application.properties(或yml)加载属性。尝试将属性从export-fields.yml移到application.yml

答案 1 :(得分:0)

添加了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);

}

}