简体   繁体   中英

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?

@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()

@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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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