gpt4 book ai didi

java - 选择在运行时 spring 注入(inject)哪个实现

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:13:46 24 4
gpt4 key购买 nike

我有以下类(class):

public interface MyInterface{}

public class MyImpl1 implements MyInterface{}

public class MyImpl2 implements MyInterface{}

public class Runner {
@Autowired private MyInterface myInterface;
}

我想做的是决定,当应用程序已经运行时(即 在启动时)应该将哪个实现注入(inject) 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();

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

最佳答案

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

然后注入(inject)它们并使用:

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

关于java - 选择在运行时 spring 注入(inject)哪个实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19231875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com