我有一个 spring 组件,它有一个 @Autowired
构造函数,该构造函数从 @Value
注释中获取参数。像这样:
@Component
public class MyImplClass implement MyInterface
...
public MyImplClass(@Value("${prop.name}") final String name, @Value("${prop.value}") final String value) {
...
}
...
在另一个类中,我像这样 Autowiring 这种类型
@Autowired
protected MyInterface _myInterface;
现在我需要获取 MyInterface bean,并将动态生成的值(在运行时生成)传递给构造函数。我尝试使用 AbstractBeanFactory
但这不起作用。我该怎么做?
最佳答案
您可以在 Spring 配置中生成一个 bean,如下所示:
@Bean
public MyInterface getMyInterfaceBean() {
// Calculate arg values
String arg1 = ...;
String arg2 = ...;
return new MyImplClass(arg1, arg2);
}
更好的解决方案是更改 MyImplClass
的构造函数以接收配置对象,该对象将知道如何加载所需的值。
关于java - 获取带有动态构造函数参数的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32252377/