0

我正在尝试应用@ConfigurationProperties注释来获取从application.yml文件到代码中我需要它的位置的映射。

这是我到目前为止的代码:

应用程序.yml

repository:
    type:
      big: big
      small: small
      medium: medium
    to:
     database:
      something: "STRING"

配置.java

@Configuration
@EnableConfigurationProperties
public class SnowflakeRepositoryConfig {

        @Bean
        @ConfigurationProperties(prefix = "repository.type")
        public DatabaseTypeMapping databaseTypeMapping() {
            return new DatabaseTypeMapping();
        }
    
        public static class DatabaseTypeMapping {
            public Map<Type, Type> typeMappingMigration;
    
            public void setMapping(Map<Type, Type> typeMappingMigration) {
                this.typeMappingMigration = typeMappingMigration; }
        }

@Bean
@ConfigurationProperties(prefix = "repository.to.database")
public BrandToDatabaseProperties brandToDatabaseProperties() {
    return new BrandToDatabaseProperties();
}

public static class BrandToDatabaseProperties {
    public Map<Brand, String> mapping;

    public void setMapping(Map<Brand, String> mapping) {
        this.mapping = mapping;
    }
}

在配置文件中,我将它应用于 serviceImpl 类,如下所示:

    @Bean
    public UserDataService getUserData(BrandToDatabaseProperties brandToDatabaseProperties, DatabaseTypeMapping databaseTypeMapping){
       return new UserDataServiceImpl(brandToDatabaseProperties.mapping, databaseTypeMapping.typeMappingMigration);
    }

serviceImpl.java类中,我像这样包含它:

    public class UserDataServiceImpl implements UserDataService {
    
        private final Map<Type, Type> typeMappingMigration;
        private final Map<Brand, String> brandToDatabaseMapping;
    
        public UserDataServiceImpl(Map<Brand, String> brandToDatabaseMapping, Map<Type, Type> typeMappingMigration) {
this.brandToDatabaseMapping = Collections.unmodifiableMap(brandToDatabaseMapping);    
            this.typeMappingMigration = Collections.unmodifiableMap(typeMappingMigration);    
        }

当我尝试启动我的应用程序时,我收到以下错误:

Failed to instantiate [service.UserDataService]: Factory method 'getUserData' threw exception; nested exception is java.lang.NullPointerException

我在这里想念什么?

4

1 回答 1

1

您不需要声明 type 的 bean DatabaseTypeMapping。将ConfigurationProperties注解移到类中,让组件扫描拾取它。或者,您可以在EnableConfigurationProperties注释中指定类名。

我不能确定,但​​我认为ConfigurationProperties不应该在方法上声明,这在逻辑上没有意义。

于 2021-11-03T15:48:45.607 回答