title: Dynamic dependency injection in spring
body: <p>I was looking for a way to create a non-singleton spring bean which can be "partially" autowired.</p>
  
  <pre><code>@Component
  class Example {
      private SpringBean1 bean1;
      private SpringBean2 bean2;
      private String dynamicDependancy;
  
      @Autowired
      public Example(SpringBean1 bean1, SpringBean2 bean2, String dynamicDepedency) {
          this.bean1 = bean1;
          this.bean2 = bean2;
          this.dynamicDepedency = dynamicDepedency;
      }
  }
  </code></pre>
  
  <p>I want such a thing because sometimes the dependency is known only in runtime.
  There is a way I have thought of which is creating a kind of a factory that create a static member class, in that way I can test the static member class:</p>
  
  <pre><code>@Component
  class ExampleFactory {
      private SpringBean1 bean1;
      private SpringBean2 bean2;
  
      @Autowired
      public ExampleFactory(SpringBean1 bean1, SpringBean2 bean2) {
          this.bean1 = bean1;
          this.bean2 = bean2;
      }
  
      public Example from(String dynamicDependency) {
          return new Example(bean1, bean2, dynamicDependency);
      }
  
      static class Example {
          private SpringBean1 bean1;
          private SpringBean2 bean2;
          private String dynamicDependancy;
  
          public Example(SpringBean1 bean1, SpringBean2 bean2, String 
              dynamicDependancy) {
              this.bean1 = bean1;
              this.bean2 = bean2;
              this.dynamicDependancy = dynamicDependancy;
          }
      }
  }
  </code></pre>
  
  <p>I was looking a bit about the Prototype scope and using getBean(java.lang.String, java.lang.Object) make it harder to use dependency injection.
  I'd like to know if there's any "Spring way" to do such things.</p>
  
  <p>Thank you.</p>
  
  <blockquote>
    <p>Update:
    I have found another solution and post an answer at another post:
    <a href="https://stackoverflow.com/a/52021965/2580829">https://stackoverflow.com/a/52021965/2580829</a></p>
  </blockquote>