Reputation: 870
Let's say I have a following bean method:
@Bean
public Queue invoiceRegenerationQueue() {
return new Queue(configurationManager.getQueue().getInvoiceRegenerationQueueName(), true);
}
and call this method somewhere in my code:
var binding = BindingBuilder
.bind(invoiceRegenerationQueue())
I have only just discovered that when I call this method I will always get the same object instead of different objects as I expected. I expected that Spring will only inject object from the context when I use @Autowired
annotation, but it seems it also cached the object which is returned from the bean method. I mean I debugged that and every call to that method returns the same object like as if spring intercepts calls to that method and returns an object from cache.
I tried to google but haven't been able yet to find any references to that in documentation. Why does it work so? Does anyone know where I can read about such behaviour in docs?
Upvotes: 1
Views: 1431
Reputation: 455
Spring uses ASM library for byte code manipulation. ConfigurationClassParser uses this library to load @Bean annotated methods.
Upvotes: 0
Reputation: 206896
I have only just discovered that when I call this method I will always get the same object instead of different objects as I expected.
That's correct. Spring modifies @Bean
methods in @Configuration
classes using bytecode manipulation techniques so that multiple calls to such a method will return the same instance - which looks strange if you look at the source code itself.
The reason is that most Spring beans are singletons, and you would not want multiple instances of those beans being created when the corresponding @Bean
method is called multiple times.
This is explained in the following section in the Spring reference documentation: Further Information About How Java-based Configuration Works Internally
Upvotes: 1