title: How to autowire FactoryBeans in an Actuator Endpoint
body: <p>I would like to know whether there are any best practices or standard patterns for autowiring factory beans themselves in Spring.</p>
  <p>I am working with <a href="https://docs.spring.io/spring-kafka/docs/current/api/org/springframework/kafka/config/StreamsBuilderFactoryBean.html" rel="nofollow noreferrer"><code>StreamsBuilderFactoryBean</code></a> which implements <code>SmartLifecycle</code>. In order to start and stop Streams at runtime, I implemented an actuator endpoint that autowires a <code>private Map&lt;String, StreamsBuilderFactoryBean&gt; topologyFactories</code>. Note, that I need the actual <code>FactoryBean</code>, not the object it creates. There seems to be an issue with the instantiation order. The <code>Map</code> is empty because Spring seems to instantiate the actuator endpoint before the FactoryBeans.</p>
  <p>I worked around this by calling</p>
  <pre><code>    @EventListener(ApplicationReadyEvent.class)
      public void onReady() {
          this.topologyFactories = ApplicationContextProvider.getApplicationContext()
                  .getBeansOfType(StreamsBuilderFactoryBean.class);
      }
  </code></pre>
  <p>and basically, autowire &quot;a second time&quot;.</p>
  <p>From <a href="https://stackoverflow.com/questions/56494641/spring-multiple-configurations-and-compontentscan-order">Spring - multiple configurations and @CompontentScan order</a> I could annotate the actuator class with <code>@DependsOn</code>, but then I would need to list every single <code>StreamsBuilderFactoryBean</code> and maintain this.</p>
  <p>It &quot;feels&quot; like there should be a better way and I am probably just missing some knowledge about the bean lifecycle.</p>