title: Choosing which bean to reference in spring?
body: <p>I have a spring project which contains a bean definition file containing a bean which references another bean as a property, for example</p>
  
  <pre><code>&lt;bean id="aBean" class="org.test.class"&gt;
      &lt;property class="org.test.A" autowire="byType"/&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p>This bean definition file will be imported by other spring projects which may or may not contain beans which extend org.test.A.</p>
  
  <p>What I'd like to do is that if an extension implementation of org.test.A exists (i.e org.test.B) I'd like to reference that in the property, otherwise just reference org.test.A.</p>
  
  <p>I have been doing some research on the matter but have not arrived at an answer. I tried writing a custom TypeFilter but that just seems to allow me to return true or false whether a class should be returned or not, rather than checking all existing bean definitions for a class and choosing one.</p>
  
  <p>Is such a thing possible? If so, how would one go about doing that?</p>
  
  <p>The idea is to avoid to have to rewrite a bunch of bean definitions which reference each other (and will for the most part all be the same in every project anyway) and only write the implementation of a referenced bean.</p>
  
  <p>Any input on the matter is appreciated.</p>
  
  <p>----- UPDATE 1 ------</p>
  
  <p>I have given it a try using @Primary and so far no luck. No errors but the class being used is not the one with @Primary.</p>
  
  <p>The main class org.test.A extends another class (org.test.Whatever), then in my servlet context I have the following</p>
  
  <pre><code>&lt;bean id="someID" class="org.someclass"&gt;
      &lt;property name="realm" ref="testBean" /&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p></p>
  
  <p>And then I created another org.test.B class which extends org.test.A and has both @Component and @Primary but no go. Spring seems to be loading the class but not using it.</p>
  
  <p>----- UPDATE 2 -----</p>
  
  <p>OK I think I know what is happening. The class which I am autowiring (Which I have no control over the source code) happens to have 2 set methods, 1 which takes a single class and one that takes a collection of that class. Spring seems to think that because it finds several beans of the same class, it should autowire the set which takes a collection instead of autowiring the set which takes a single instance.</p>
  
  <p>How do I specify, in the context xml which I am instancing the class, which method should be autowired? I don't understand why spring won't allow me to use autowire attribute on a property. I can only set autowire on the bean which leaves spring to choose which method to autowire. :S</p>