title: Thread-safeness and resource leaking in a @Configuration class
body: <p>I had to create a singleton bean manually in a <code>@Configuration</code> 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:</p>
  
  <ul>
  <li>Thread Safeness: The Datasource object is not stateless</li>
  <li>Resource leaking: The Datasource object is not explictly closed by the context</li>
  </ul>
  
  <p>The code is the following:</p>
  
  <pre><code>    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());
      }
  </code></pre>
  
  <p>My question is: Do I really have a risk to overlook this? Isn't Spring smart enough? </p>
  
  <ul>
  <li><p>Regarding thread safeness, I understand that for my code to be
  problematic, there should happen 2 threads processing the
  @Configuration. Does Spring does that?? </p></li>
  <li><p>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?</p></li>
  </ul>
  
  <p>How would you make safer this code?</p>