问题描述
在 Spring Boot 应用程序中,我有以下结构
动态绑定在默认 noargsconstructor
下工作正常,直到我不得不进行更改并在运行时将 String
传递给构造函数,如下所示。
@Component
class ClassA extends AbstractClass implements MyInterface {
public static final String IMPLEMENTATION = "A";
public ClassA(String val) {
super(val);
}
public String getImplementation() {
return ClassA.IMPLEMENTATION;
}
}
@Component
class ClassB extends AbstractClass implements MyInterface {
public static final String IMPLEMENTATION = "B";
public ClassB(String val) {
super(val);
}
public String getImplementation() {
return ClassB.IMPLEMENTATION;
}
}
interface MyInterface {
public String getImplementation();
public String performOperation();
}
abstract class AbstractClass{
public AbstractClass(String val) {
System.out.println(val); //some other operation on runtime String val
}
public String performOperation() {
//do something here or (in ClassA AND ClassB)
return "";
}
}
@Component
public class MyInterfaceHolder {
private final Map<String,MyInterface> myInterfaceMap;
public MyInterfaceHolder(List<MyInterface> myInterfaceList) {
myInterfaceMap = myInterfaceList.stream().collect(Collectors.toMap(MyInterface::getImplementation,Function.identity()));
}
public MyInterface getImplementation(String implementationType) { //implementationType = "A" || "B"
MyInterface myInterface = myInterfaceMap.get(implementationType);
return myInterface;
}
}
@Service
public class MyService implements ServiceInterface {
@Autowired
MyInterfaceHolder myInterfaceHolder;
@Override
public String performOperation(String val) {
myInterfaceHolder.getImplementation(val).performOperation();
}
}
现在我明白了这个问题,Spring 试图在应用程序启动时将一个 String 类型的对象映射到 ClassA
和 ClassB
构造函数参数。但该 String 值仅在运行时创建。所以,当它在启动过程中没有发现 String Object 时,它就会出错。
我需要的是在运行时动态创建 ClassA
和 ClassB
bean,并在这样做时将运行时值 (String val
) 注入构造函数。我该如何存档?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)