我想在 Spring Java 配置 中创建一个 Spring bean,并在运行时传递一些构造函数参数。我创建了以下 Java 配置,其中有一个 bean fixedLengthReport 需要构造函数中的一些参数。
@Configuration
public class AppConfig {
@Autowrire
Dao dao;
@Bean
@Scope(value = "prototype")
**//SourceSystem can change at runtime**
public FixedLengthReport fixedLengthReport(String sourceSystem) {
return new TdctFixedLengthReport(sourceSystem, dao);
}
}
但是我收到错误消息,因为没有找到 bean, 所以 sourceSystem 无法连接。如何使用运行时构造函数参数创建 bean?
我正在使用 Spring 4.2
原文由 suraj bahl 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以将原型 bean 与
BeanFactory
一起使用。@Scope(value = "prototype")
意味着 Spring 不会在开始时立即实例化 bean,但稍后会根据需要进行实例化。现在,要自定义原型 bean 的实例,您必须执行以下操作。注意,因为你的 bean 不能在启动时实例化,所以你不能直接自动装配你的 bean;否则 Spring 将尝试实例化 bean 本身。这种用法会导致错误。