I had to create a singleton bean manually in a @Configuration
class in order to share it without exposing it into the context (which triggers conditionals/autoconfigures). I have been pointed to the awareness of certain risks to manage it by myself:
- Thread Safeness: The Datasource object is not stateless
- Resource leaking: The Datasource object is not explictly closed by the context
The code is the following:
private DataSource nonExposedDatasource;
public DataSource nonExposedSingletonDataSource() {
if (Objects.isNull(this.nonExposedDatasource)) {
this.nonExposedDatasource = this.myPrivateDatasourceProperties.initializeDataSourceBuilder().build();
}
return this.nonExposedDatasource;
}
@Bean
public TaskConfigurer taskConfigurer() {
return new DefaultTaskConfigurer(this.nonExposedSingletonDataSource());
}
@Bean
public BatchConfigurer batchConfigurer() {
return new DefaultBatchConfigurer(this.nonExposedSingletonDataSource());
}
My question is: Do I really have a risk to overlook this? Isn't Spring smart enough?
Regarding thread safeness, I understand that for my code to be problematic, there should happen 2 threads processing the @Configuration. Does Spring does that??
Regarding resource leaking, if my Datasource had been a @Bean managed by Spring, like most applications work, wouldn't have been this a potential pitfall if the app closes anyway?
How would you make safer this code?