090 Faq How Bean Works Behind The Scenes
090 Faq How Bean Works Behind The Scenes
the scenes
Question:
During All Java Configuration, how does the @Bean annotation work in
the background?
Answer
This is an advanced concept. But I'll walk through the code line-by-line.
This specifies that the bean will bean id of "swimCoach". The method
name determines the bean id. The return type is the Coach interface.
This is useful for dependency injection. This can help Spring find any
dependencies that implement the Coach interface.
1. return mySwimCoach;
----
Now let's step back and look at the method in it's entirety.
1. @Bean
2. public Coach swimCoach() {
3. SwimCoach mySwimCoach = new SwimCoach();
4. return mySwimCoach;
5. }
It is important to note that this method has the @Bean annotation. The
annotation will intercept ALL calls to the method "swimCoach()". Since
no scope is specified the @Bean annotation uses singleton scope.
Behind the scenes, during the @Bean interception, it will check in
memory of the Spring container (applicationContext) and see if this
given bean has already been created.
If this is the first time the bean has been created then it will execute the
method as normal. It will also register the bean in the application
context. So that is knows that the bean has already been created
before. Effectively setting a flag.
The next time this method is called, the @Bean annotation will check in
memory of the Spring container (applicationContext) and see if this
given bean has already been created. Since the bean has already been
created (previous paragraph) then it will immediately return the instance
from memory. It will not execute the code inside of the method. Hence
this is a singleton bean.
====
>> Please explain in detail whats happening behind the scene for
this statement.
1. return new SwimCoach(sadFortuneService())
The code
1. // define bean for our sad fortune service
2. @Bean
3. public FortuneService sadFortuneService() {
4. return new SadFortuneService();
5. }
In the code above, we define a bean for the sad fortune service. Since
the bean scope is not specified, it defaults to singleton.
---
This concludes the line-by-line discussion of the source code. All of the
behind the scenes work.