我有一个 Spring Boot 应用程序,在其中使用“原型(prototype)”bean。 我知道可以通过构造函数参数注入(inject)参数 但我想避免这种方法,因为我有一些额外的 配置参数,包括其他 Bean 和我的每个实例参数。
public class FooBar {
// singleton beans that are shared between multiple instances of this class
private FooRepository fooRepository;
private BarRepository barRepository;
// instance specific settings that are SPECIFIC to the instance of this class
private String fooParameter;
private String barParameter;
private String parameterX;
private String parameterY;
private String parameterZ;
//...
}
@Configuration
public class AppConfig {
/* @Bean definition of FooRepository, BarRepository etc */
@Bean
@Scope(value = "prototype")
public FooBar getFoobar(
FooRepository fooRepository, BarRepository barRepository,
String fooParameter, String barParameter, String parameterX /* ... */) {
// works, but I want to avoid something like this
return new new Foobar(fooRepository, barRepository,
fooParameter, barParameter, parameterX, /* ... */);
}
@Bean
@Scope(value = "prototype")
public FooBar getFoobar(HashMap<String, String> moreParameters) {
Foobar foobar = new Foobar();
// inject parameters without having to implement setter calls
// I want to inject BOTH Spring Beans here and some config parameters
return foobar;
}
}
有没有办法让 Spring 从其内部集合中进行 Autowiring bean 和我提供的参数也是如此?我想完全避免必须进行 setter 调用。
最佳答案
不,不幸的是没有其他方法可以进行依赖注入(inject)
!即使在 Spring 官方文档中也明确指出实现是根据构造函数或 setter 进行的,但是极其重要的是,特别注意SETTER
。
@Autowirder
public void settter(){}
关于java - Spring Boot原型(prototype)bean : injection from Spring Context and supplied parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61834663/