Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use @Autowired to dynamically inject implementation like a factory pattern
    text
    copied!<p>I am fairly new to Sprint and am using Spring 3.x and roo1.1.1 for my application.</p> <p>I have multiple implementation of an interface which would be @Autowired into other different classes. I would only be able to decide which implementation to go with at the runtime. This should be achieved with like a factory pattern.</p> <pre><code>public interface SomeInterface { public void doSomething(); } </code></pre> <p>Implementation 1.</p> <pre><code>public class SomeOb implements SomeInterface { public void doSomething() { //Do something for first implementation here } } </code></pre> <p>Implementation 2.</p> <pre><code>public class SomeOtherOb implements SomeInterface { public void doSomething() { //Do something for first implementation here } } </code></pre> <p>Now in my service i needed this Autowired like</p> <pre><code>@Service public class MyService { @Autowired SomeInterface ob; //Rest of the code here } </code></pre> <p>1) The logic to choose which implementation to be Autowired is only know runtime, so i cannot use the @Qualifier annotation to qualify this. 2) I tried to create a FactoryBean like </p> <pre><code>public class SomeFactoryBean implements FactoryBean&lt;SomeInterface&gt; { @Override public SomeInterface getObject() throws Exception { if(/*Somecondition*/) { return new SomeOb(); } else return new SomeOtherOb(); } @Override public Class&lt;? extends SomeInterface&gt; getObjectType() { if(/*Somecondition*/) { return SomeOb.class; } else return SomeOtherOb.class; } @Override public boolean isSingleton() { return false; } } </code></pre> <p>In the applicationContext.xml i have the tag mentioned.</p> <p>When i run the webserver i run into an error like </p> <pre><code>No unique bean of type [com.xxxx.xxxx.SomeInterface] is defined: expected single matching bean but found 3: [xxxx, xxxxxxx, xxxxFactory] </code></pre> <p>Can anyone please help me to resolve this issue. If i am not doing this right please direct me to do this the right way.</p> <p>Thanks and appreciate any help, jjk</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload