Spring Boot @ConfigurationProperties 不注入

Springboot @ConfigurationProperties Not Injecting

我无法将我的 属性 文件 (export-fields.yml) 注入地图。我在资源文件夹中创建了属性文件,链接到 属性 源,为 属性 对象创建了一个配置,并使用 lombok 生成了 getter 和 setter,但仍然没有得到任何填充到字段映射(字段 = 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);
    }
}

导出-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);

}

}