简体   繁体   English

将Spring Boot bean注入bean注入方法

[英]Spring boot bean into bean injection methodology

Can anyone tell me if there is a difference (in terms of spring bean injection and respecting singleton conditions or any other spring boot magic) in these two spring boot application classes? 谁能告诉我这两个Spring Boot应用程序类之间是否有区别(在Spring bean注入和尊重单例条件或其他任何Spring Boot魔术方面)?

@Bean
@Scope("singleton")
public UserService userService(Foo foo){
    return new UserService(foo);
}

@Bean
@Scope("singleton")
public Foo foo(){
    return new Foo();
}

AND calling not declaring Foo as a method parameter on userService() but rather injecting it via a direct method call to foo() AND调用不是将Foo声明为userService()上的方法参数,而是通过对foo()的直接方法调用将其注入

@Bean
@Scope("singleton")
public UserService userService(){
    return new UserService(foo());
}

@Bean
@Scope("singleton")
public Foo foo(){
    return new Foo();
}

No, there is no difference. 不,没有区别。 One might think, you would get a new bean instance everytime you call foo() in that configuration class, but the way Spring works in that case is, it creates a proxy for that configuration class which intercepts all method calls. 可能会想到,每次在该配置类中调用foo()时,您都会得到一个新的bean实例,但是在这种情况下,Spring的工作方式是,为该配置类创建一个代理,以拦截所有方法调用。 The proxy then checks, if there is already a bean of type Foo , if so it returns the existing instance, otherwise the method call is delegated to the implementation and a new bean is created. 然后,代理检查是否已经存在类型为Foo的bean,如果是,它将返回现有实例,否则将方法调用委托给实现并创建一个新bean。

Code style wise, however, i think in your first example the dependency to the Foo bean is more clearly marked than in the second example. 但是,在代码风格方面,我认为在第一个示例中比在第二个示例中更清楚地标记了对Foo bean的依赖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM