Spring 如何使用@Autowired像工厂模式一样动态注入实现
我是Sprint的新手,我的应用程序使用Spring3.x和roo1.1.1 我有一个接口的多个实现,它可以@Autowired到其他不同的类中。我只能在运行时决定使用哪个实现。这应该像工厂模式一样实现Spring 如何使用@Autowired像工厂模式一样动态注入实现,spring,autowired,Spring,Autowired,我是Sprint的新手,我的应用程序使用Spring3.x和roo1.1.1 我有一个接口的多个实现,它可以@Autowired到其他不同的类中。我只能在运行时决定使用哪个实现。这应该像工厂模式一样实现 public interface SomeInterface { public void doSomething(); } 执行情况1 public class SomeOb implements SomeInterface { public void doSomething(
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
}
}
现在在我的服务中,我需要像这样的自动连线
@Service
public class MyService {
@Autowired
SomeInterface ob;
//Rest of the code here
}
1) 选择要自动连接的实现的逻辑是“只知道运行时”,因此我不能使用@Qualifier注释来限定它。
2) 我试图创建一个类似FactoryBean的
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;
}
}
谁能帮我解决这个问题。如果我做得不对,请指示我以正确的方式做这件事
感谢并感谢您的帮助,
如果应用程序的给定实例只需要一个bean实现,jjk将isSingleton()返回true 但我怀疑你的设计 我总是使用属性文件来切换这样的实现。我曾经不得不为一个站点实施验证码集成。我们使用JCaptcah和ReCAPTCHA API进行原型设计。我创建了一个新的界面,其中只包含我们需要的功能,然后为这两个API创建了实现。使用Spring配置文件和Maven概要文件中的占位符,我们可以在编译时或部署时切换实现类,例如,mvn jetty:run-DcaptchaImpl=recaptcha或-DcaptchaImpl=jcaptcha
如果不知道你想完成的任务,就很难提供更多的建议。谢谢你的建议。我在同事的帮助下解决了这个问题。我做错了什么
No unique bean of type [com.xxxx.xxxx.SomeInterface] is defined: expected single matching bean but found 3: [xxxx, xxxxxxx, xxxxFactory]