如何解决动态注入具有使用运行时参数的构造函数的 bean
在 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 举报,一经查实,本站将立刻删除。