简体   繁体   English

在 Spring 引导自动配置中使用子 class 扩展数据源

[英]Extending DataSource with a sub class in Spring Boot AutoConfiguration

I'm trying to write an auto-configuration library that adds functionality to any DataSource .我正在尝试编写一个自动配置库,为任何DataSource添加功能。 I've written a sub-class that I'll call CustomDataSource here and which overrides some of the methods of DataSource .我编写了一个子类,我将在这里调用CustomDataSource并覆盖DataSource的一些方法。

@Configuration
@ConditionalOnBean(DataSource.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class CustomDataSourceAutoConfiguration {

    private final DataSource dataSource;

    public CustomDataSourceAutoConfiguration(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Primary
    @Bean
    public CustomDataSource customDataSource() {
        return new CustomDataSource(dataSource);
    }
}

But I can't find a way that allows me to do what I want.但我找不到让我做我想做的事的方法。 It will always result in a circular reference and the exception:它总是会导致循环引用和异常:

BeanCurrentlyInCreationException: Error creating bean with name 'customDataSource': Requested bean is currently in creation: Is there an unresolvable circular reference?

Is there a way around this?有没有解决的办法?

I found a way to work around this issue by implementing a BeanPostProcessor :我找到了一种通过实现BeanPostProcessor来解决此问题的方法:

public class DataSourcePostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if (bean instanceof DataSource && !(bean instanceof CustomDataSource)) {
            return new CustomDataSource((DataSource) bean);
        } else {
            return bean;
        }
    }

}

The postProcessAfterInitialization method can explicitly be used for wrapping beans in a proxy, citing from the BeanPostProcessor documentation : postProcessAfterInitialization方法可以显式用于将 bean 包装在代理中,引用BeanPostProcessor文档

[...] post-processors that wrap beans with proxies will normally implement postProcessAfterInitialization(java.lang.Object, java.lang.String) . [...] 使用代理包装 bean 的后处理器通常会实现postProcessAfterInitialization(java.lang.Object, java.lang.String)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM