gpt4 book ai didi

java - 如何在运行时选择 Spring bean 实例

转载 作者:IT老高 更新时间:2023-10-28 13:49:07 25 4
gpt4 key购买 nike

根据传递给方法的参数,我需要从许多 Spring bean 中选择一个,它们是同一类的实现,但配置了不同的参数。

例如如果用户 A 调用该方法,我需要在 bean A 上调用 dooFoo(),但如果是用户 B,那么我需要在 bean B 上调用相同的方法。

除了将所有 bean 粘贴在映射中并从传递给我的方法的参数中派生 key 之外,是否还有一种“更灵活”的方法?

最佳答案

我们在项目中遇到了这个问题,我们通过类似工厂的类来解决它。客户端类——在运行时需要 bean——有一个工厂的实例,它是通过 Spring 注入(inject)的:

@Component
public class ImTheClient{

@Autowired
private ImTheFactory factory;

public void doSomething(
Parameters parameters) throws Exception{
IWantThis theInstance = factory.getInstance(parameters);

}

}

所以,IWantThis实例取决于 parameters 的运行时值范围。工厂实现是这样的:

@Component
public class ImTheFactoryImpl implements
ImTheFactory {

@Autowired
private IWantThisBadly anInstance;
@Autowired
private IAlsoWantThis anotherInstance;

@Override
public IWantThis getInstance(Parameters parameters) {
if (parameters.equals(Parameters.THIS)) {
return anInstance;
}

if (parameters.equals(Parameters.THAT)) {
return anotherInstance;
}

return null;
}
}

因此,工厂实例持有对 IWantThis 的两个可能值的引用。类,是 IWantThisBadlyIAlsoWantThis IWantThis 的两种实现.

关于java - 如何在运行时选择 Spring bean 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17702031/

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