I have spring boot application which uses application.yml for configuration. The structure is something like:
...
rmq:
host: "host"
port: 5672
...
In my code I have ApplicationConfig class which looks like below:
@AllArgsConstructor
class ApplicationConfig {
private RabbitConfig rabbitConfig;
}
@ConfigurationProperties(prefix = "rmq")
class RabbitConfig {
@NotNull
private String host;
@NotNull
private Integer port;
}
The problem is that section rmq is optional in my application. And I want field rabbitConfig will init by null in case it is absent in application.yml.
But really if I drop rmq section in config file I've got an error (rmq.host is absent). Is it possible to force springboot to init rabbitConfig with null in that case?
CodePudding user response:
You can use @ConditionalOnProperty
for such cases. In your case, you should define it as:
@ConfigurationProperties(prefix = "rmq")
@ConditionalOnProperty(prefix = "rmq", name = "host", matchIfMissing = true)
class RabbitConfig {
@NotNull
private String host;
@NotNull
private Integer port;
}
Then it will load the bean only if there is rmq.host
set, and if not, it will be set to null
.
There is also an alternative that you always put i.e. rmq.enabled = true | false, and then @ConditionalOnProperty(prefix = "rmq", name = "host", havingValue = true)