1

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();
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I agree that the first style is clearly marked however we have always gone with the second style because it allows us to CTRL-click in intellij to quick browse to the foo() injector... thereby quickly traversing the dependency injection tree.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.