我正在做一个由其他项目使用的库。这个库通过JDBC提供数据库访问,我也想在同一个库中添加对R2DBC的支持。消费项目应该能够基于配置属性在JDBC和R2DBC之间切换。
我面临的问题是,由R2DBC (2.5.4)提供的spring-boot-starter-data-r2dbc自动配置覆盖了JDBC配置,而消费项目只能使用R2DBC。
此外,在构建项目时,有些任务(如文档或代码生成、测试等)依赖于加载的spring上下文,但不需要数据库访问。这些任务失败,因为由于缺少R2DBC属性,无法加载上下文:
BeanCreationException: Error creating bean with name 'connectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/r2dbc/ConnectionFactoryConfigurations$Pool.class]: Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.r2dbc.pool.ConnectionPool]: Factory method 'connectionFactory' threw exception;
nested exception is org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryOptionsInitializer$ConnectionFactoryBeanCreationException: Failed to determine a suitable R2DBC Connection URL当然,我可以指定所需的属性,但是加载我不使用的组件并不合适。我想完全禁用R2DBC (就像你可以用spring.cloud.vault.enabled=false禁用Vault支持一样),并且只在我需要的时候加载它。对怎么做有什么想法吗?
发布于 2022-01-12 12:52:46
我的第一个尝试是在库中创建一个配置类:
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "r2dbc.enabled", havingValue = "false", matchIfMissing = true)
@AutoConfigureBefore(R2dbcAutoConfiguration.class)
@EnableAutoConfiguration(exclude = R2dbcAutoConfiguration.class)
public class R2dbcConfig {}这在一些任务中起到了作用,但在另一些任务中却造成了问题。我张贴它,因为它可能是足够的一些人。
在我的所有情况下,解决方案都更复杂一些,我必须实现一个EnvironmentPostProcessor,将org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration添加到spring.autoconfigure.exclude属性中。很快,像这样的事情:
public class R2dbcDisablerEnvironmentPostProcessor implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
Properties props = new Properties();
props.setProperty("spring.autoconfigure.exclude", "org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration");
environment.getPropertySources()
.addLast(new PropertiesPropertySource("r2dbcProperties", props));
}
}谢谢@xerx593 593的指针!
https://stackoverflow.com/questions/70655257
复制相似问题