【发布时间】:2011-04-20 03:37:12
【问题描述】:
我是 Sprint 的新手,我的应用程序使用 Spring 3.x 和 roo1.1.1。
我有一个接口的多个实现,可以@Autowired 到其他不同的类中。我只能在运行时决定使用哪个实现。这应该通过类似工厂模式来实现。
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
}
}
现在在我的服务中,我需要像这样的 Autowired
@Service
public class MyService {
@Autowired
SomeInterface ob;
//Rest of the code here
}
1) 选择要自动装配的实现的逻辑只知道运行时,所以我不能使用@Qualifier 注释来限定它。 2)我试图创建一个像
的 FactoryBeanpublic 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 中我提到了标签。
当我运行网络服务器时,我遇到了类似的错误
No unique bean of type [com.xxxx.xxxx.SomeInterface] is defined: expected single matching bean but found 3: [xxxx, xxxxxxx, xxxxFactory]
谁能帮我解决这个问题。如果我做的不对,请指导我以正确的方式做。
感谢并感谢任何帮助, jjk
【问题讨论】: