Java 选择在运行时注入哪个实现 spring

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19231875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:17:29  来源:igfitidea点击:

Choose which implementation to inject at runtime spring

javaspringdependency-injection

提问by kwh

I have the following classes:

我有以下课程:

public interface MyInterface{}

public class MyImpl1 implements MyInterface{}

public class MyImpl2 implements MyInterface{}

public class Runner {
        @Autowired private MyInterface myInterface;
}

What I want to do is decide, whilst the app is already running (i.e. notat startup) which Implementation should be injected into Runner.

我想要做的是决定,当应用程序已经在运行(即不在启动时)时,应该将哪个实现注入到Runner.

So ideally something like this:

所以理想情况下是这样的:

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();

What is the best way to accomplish this?

实现这一目标的最佳方法是什么?

采纳答案by acc15

Declare implementations with @Component("implForRq1")and @Component("implForRq2")

使用@Component("implForRq1")和声明实现@Component("implForRq2")

Then inject them both and use:

然后注入它们并使用:

class Runner {

    @Autowired @Qualifier("implForRq1")
    private MyInterface runnerOfRq1;

    @Autowired @Qualifier("implForRq2")
    private MyInterface runnerOfRq2;

    void run(int rq) {
        switch (rq) {
            case 1: runnerOfRq1.run();
            case 2: runnerOfRq2.run();
            ...

        }
    }

}

...

@Autowired
Runner runner;

void run(int rq) {
    runner.run(rq);
}