title: @Conditional on bean initialization
body: <p>I have been searching for this for a while.</p>
  
  <p>Till now, I found <a href="https://www.intertech.com/Blog/spring-4-conditional-bean-configuration/" rel="nofollow noreferrer">this</a> blog very useful but did not solve my problem.</p>
  
  <p>I want to <code>@Autowired</code> a bean only if a <code>flag</code> is true, else I want that to be <code>null</code></p>
  
  <p><strong>Use Case:</strong></p>
  
  <p>If one of the DB is under maintenance, I do not want my app to fail.</p>
  
  <pre><code>@Bean("sqlDatabase")
  public Database getSqlDatabase(@Value("${datasource.sql.url}") String url,
          @Value("${datasource.sql.username}") String username, @Value("${datasource.sql.password}") String password,
          @Value("${datasource.poolsize.min}") int minPoolSize, @Value("${datasource.poolsize.max}") int maxPoolSize,
          @Value("${database.enable-sql}") boolean isSqlEnabled) {
      if (isSqlEnabled)
          return Database.builder().url(url).pool(minPoolSize, maxPoolSize).username(username).password(password)
                  .build();
      else
          return null;
  }
  </code></pre>
  
  <p>Now, in this case, its throwing error as I cannot <code>autowire</code> a <code>null</code> bean.</p>
  
  <p>I wanted to use <code>@Conditional</code> but my case is a bit complex. I already need all 3 databases to be updated. I just want to <code>skip</code> one of them if conditions are not met.</p>