简体   繁体   中英

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 . I've written a sub-class that I'll call CustomDataSource here and which overrides some of the methods of 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 :

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 :

[...] post-processors that wrap beans with proxies will normally implement postProcessAfterInitialization(java.lang.Object, java.lang.String) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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