【发布时间】:2013-10-07 18:21:17
【问题描述】:
我有以下课程:
public interface MyInterface{}
public class MyImpl1 implements MyInterface{}
public class MyImpl2 implements MyInterface{}
public class Runner {
@Autowired private MyInterface myInterface;
}
我想做的是决定,当应用程序已经在运行时(即不是在启动时)应该将哪个实现注入Runner。
理想情况下是这样的:
ApplicationContext appContext = ...
Integer request = ...
Runner runner = null;
if (request == 1) {
//here the property 'myInterface' of 'Runner' would be injected with MyImpl1
runner = appContext.getBean(Runner.class)
}
else if (request == 2) {
//here the property 'myInterface' of 'Runner' would be injected with MyImpl2
runner = appContext.getBean(Runner.class)
}
runner.start();
最好的方法是什么?
【问题讨论】:
-
这种方式违背了 IoC 和依赖注入的目的。
-
您是在使用 XML 配置还是组件扫描?
-
@ToddMurray 所有注释驱动,根本没有 XML。
-
在启动时同时注入,然后在运行时在实现之间切换。
-
您可以使用使用 spring 配置的工厂模式并在运行时选择实现。
标签: java spring dependency-injection