如何使用@Autowired像工厂模式一样动态注入实现 [英] How to use @Autowired to dynamically inject implementation like a factory pattern
问题描述
我对Sprint还是一个新手,正在为我的应用程序使用Spring 3.x和roo1.1.1.
I am fairly new to Sprint and am using Spring 3.x and roo1.1.1 for my application.
我有一个接口的多种实现,可以@Autowired到其他不同的类中.我只能在运行时决定要使用哪种实现.这应该通过工厂模式来实现.
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.
public interface SomeInterface {
public void doSomething();
}
实施1.
public class SomeOb implements SomeInterface {
public void doSomething() {
//Do something for first implementation here
}
}
实施2.
public class SomeOtherOb implements SomeInterface {
public void doSomething() {
//Do something for first implementation here
}
}
现在在我的服务中,我需要像这样的自动接线
Now in my service i needed this Autowired like
@Service
public class MyService {
@Autowired
SomeInterface ob;
//Rest of the code here
}
1)选择要自动接线的实现的逻辑仅知道运行时,因此我无法使用@Qualifier注释对此进行限定. 2)我试图创建一个像
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
public class SomeFactoryBean implements FactoryBean<SomeInterface> {
@Override
public SomeInterface getObject() throws Exception {
if(/*Somecondition*/) {
return new SomeOb();
} else
return new SomeOtherOb();
}
@Override
public Class<? extends SomeInterface> getObjectType() {
if(/*Somecondition*/) {
return SomeOb.class;
} else
return SomeOtherOb.class;
}
@Override
public boolean isSingleton() {
return false;
}
}
在applicationContext.xml中,我提到了标签.
In the applicationContext.xml i have the tag mentioned.
当我运行网络服务器时,我会遇到类似
When i run the webserver i run into an error like
No unique bean of type [com.xxxx.xxxx.SomeInterface] is defined: expected single matching bean but found 3: [xxxx, xxxxxxx, xxxxFactory]
任何人都可以帮助我解决此问题.如果我没有正确执行此操作,请指示我正确执行此操作.
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.
感谢并感谢您的帮助, jjk
Thanks and appreciate any help, jjk
推荐答案
感谢您的建议.在同事的帮助下,我得以解决了这个问题.我做错了
Thanks for the suggestion. I was able to solve the problem with help from a colleague. What i was doing wrong
- 我使用@Service实现了SomeInterface.因此,弹簧扫描器将其拾取并添加到Bean中.
- 在反复试验中,我从FactoryBean实现中删除了@Component注释.
进行了这些更改后,它就像是一种魅力.
After making these changes it worked like a charm.
这篇关于如何使用@Autowired像工厂模式一样动态注入实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!