Reputation: 2045
I am trying to apply @ConfigurationProperties
annotation to get a map from application.yml
file to places in code where I need it.
Here is the code I have so far:
application.yml
repository:
type:
big: big
small: small
medium: medium
to:
database:
something: "STRING"
configuration.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;
}
}
And in config file I am applying it to serviceImpl class like this:
@Bean
public UserDataService getUserData(BrandToDatabaseProperties brandToDatabaseProperties, DatabaseTypeMapping databaseTypeMapping){
return new UserDataServiceImpl(brandToDatabaseProperties.mapping, databaseTypeMapping.typeMappingMigration);
}
In serviceImpl.java class, I include it like this:
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);
}
When I try to start my application, I am getting the following error:
Failed to instantiate [service.UserDataService]: Factory method 'getUserData' threw exception; nested exception is java.lang.NullPointerException
What am I missing here?
Upvotes: 0
Views: 1872
Reputation: 24518
You don’t need to declare a bean of type DatabaseTypeMapping
. Move the ConfigurationProperties
annotation to the class, and let component scan pick it up. Alternatively, you can specify the class name in the EnableConfigurationProperties
annotation.
I can’t be sure but I think ConfigurationProperties
isn’t supposed to be declared on a method, it doesn’t make sense logically.
Upvotes: 1