[英]Spring Boot prototype bean: injection from Spring Context and supplied parameters
I have a Spring Boot application, in which I use "prototype" beans.我有一个 Spring Boot 应用程序,我在其中使用“原型”bean。 I know it is possible to inject parameters through constructors arguments but I would like to avoid the approach, as I have a number of additional configuration parameters, including other Beans AND my per-instace parameters.
我知道可以通过构造函数 arguments 注入参数,但我想避免这种方法,因为我有许多额外的配置参数,包括其他 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;
}
}
Is there any way to get Spring to do the Autowiring from its internal set of Beans AND my provided parameters as well?有没有办法让 Spring 从它的内部 Bean 集和我提供的参数中进行自动装配? I want to avoid having to setter calls completely.
我想避免必须完全调用 setter。
No, unfortunately there is no other way to make dependency injection
!不,不幸的是没有其他方法可以进行
dependency injection
! Even in the official Spring
documentation it is clearly indicated that the implementation takes place according to the constructor
or the setter
, BUT what is extremely important, attention is paid specifically to SETTER
.即使在官方
Spring
文档中也清楚地表明实现是根据constructor
或setter
进行的,但是非常重要的是,特别注意SETTER
。
@Autowirder
public void settter(){}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.