我有spring引导应用程序,它使用application.yml进行配置。其结构类似于:
...
rmq:
host: "host"
port: 5672
...在我的代码中,我有ApplicationConfig类,如下所示:
@AllArgsConstructor
class ApplicationConfig {
private RabbitConfig rabbitConfig;
}
@ConfigurationProperties(prefix = "rmq")
class RabbitConfig {
@NotNull
private String host;
@NotNull
private Integer port;
}问题是rmq在我的应用程序中是可选的。如果rabbitConfig字段在application.yml中不存在,那么它将被null插入。
但实际上,如果我将rmq部分删除到配置文件中,则会出现一个错误(没有rmq.host)。在这种情况下,是否有可能使用null将springboot引导到init rabbitConfig?
发布于 2022-11-07 23:13:03
对于这种情况,您可以使用@ConditionalOnProperty。在您的情况下,您应该将其定义为:
@ConfigurationProperties(prefix = "rmq")
@ConditionalOnProperty(prefix = "rmq", name = "host", matchIfMissing = true)
class RabbitConfig {
@NotNull
private String host;
@NotNull
private Integer port;
}然后,只有在存在rmq.host集的情况下,它才会加载bean,如果不是,它将被设置为null。
还有一种可选的方法,您总是把它放在rmq.enabled = true \ false,然后是@ConditionalOnProperty(prefix = "rmq", name = "host", havingValue = true)
https://stackoverflow.com/questions/74353887
复制相似问题