I am trying bind properties from yml file to object by using inheritance but getting null values in binding.
I have three classes, StoreConfig is superclass, MessageStoreConfig is subclass and MongodbMessageStore is also subclass of MessageStoreConfig.
@ConfigurationProperties(prefix = "store")
public class StoreConfig {}
@ConfigurationProperties(prefix = "messagestore")
public class MessageStoreConfig extends StoreConfig {}
@Component
@ConfigurationProperties(prefix = "config.mongodb")
public class MongoDbMessageStoreConfig extends MessageStoreConfig {
@Value("${connection_string}")
private String connectionString;
public String getConnectionString() {
return connectionString;
}
public void setConnectionString(String connectionString) {
this.connectionString = connectionString;
}
}
application.yml file
store:
messagestore:
config:
mongodb:
connection_string: mongodb://localhost:27017
I am getting below error.
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'connection_string' in value "${connection_string}"
Am i doing the right thing or spring does not support this kind of binding?
CodePudding user response:
Spring does not work this way. First of all you should not mix @ConfigurationProperties
and @Value
. They are two different ways of importing configuration from properties. So even if you annotated your class like this:
@ConfigurationProperties(prefix = "store.messagestore.config.mongodb")
and then use @Value("${connection_string}")
it still would not work because @Value
and @ConfigurationProperties
can not be mixed.
Similar question is discussed here: https://github.com/spring-projects/spring-boot/issues/2254
Also extending a class which is annotated with @ConfigurationProperties
with another class which is also annotated with @ConfigurationProperties
does not mean that prefixes will be concatenated together. This means that Spring expects multiple sets of properties from you (ones of the superclass and ones of the subclass) and they are not related to each other at all.