【发布时间】:2017-07-07 20:12:47
【问题描述】:
我一直在寻找这个。
到目前为止,我发现this 博客非常有用,但并没有解决我的问题。
只有当flag 为真时,我才想@Autowired 一个bean,否则我希望它是null
用例:
如果其中一个数据库正在维护中,我不希望我的应用失败。
@Bean("sqlDatabase")
public Database getSqlDatabase(@Value("${datasource.sql.url}") String url,
@Value("${datasource.sql.username}") String username, @Value("${datasource.sql.password}") String password,
@Value("${datasource.poolsize.min}") int minPoolSize, @Value("${datasource.poolsize.max}") int maxPoolSize,
@Value("${database.enable-sql}") boolean isSqlEnabled) {
if (isSqlEnabled)
return Database.builder().url(url).pool(minPoolSize, maxPoolSize).username(username).password(password)
.build();
else
return null;
}
现在,在这种情况下,它会抛出错误,因为我不能 autowire a null bean。
我想使用@Conditional,但我的情况有点复杂。我已经需要更新所有 3 个数据库。如果条件不满足我只想skip其中一个。
【问题讨论】:
-
我已经需要更新所有 3 个数据库。如果条件不满足,我只想跳过其中一个。。你能详细说明一下你的意思吗?
-
我有一个涉及 3 个数据库的 Spring Boot 应用程序。我正在为它们创建 3 种不同的 bean。现在让我们说进行维护,我们要关闭一个数据库,我仍然需要休息 2。在博客的示例中。
EITHER-OR确实不适用于我的情况。我只是不希望我的初始化因尝试连接超时而挂起。
标签: java spring spring-boot conditional autowired