Calling a @Bean annotated method in Spring java configuration
Make a direct invocation of a @Bean
method in your Spring config class to recycle the bean instance handled by Spring's context, thus ensuring the singleton scope of your beans. Hooray for recycling!
Don't forget: direct calls abide by Spring's DI and lifecycle contracts, avoiding the cloning hell.
Need to break the laws of singletons for a change, use prototype scope with @Scope("prototype")
on your @Bean
method, and Spring will create and give you a fresh instance at each call. Who ever said there were no second chances?
Have you always dreamed of rebel methods that ignore proxy rules? Your dreams came true with static methods tagged with @Bean
. No more proxy interference, just pure class body execution.
CGLIB proxying 101
You ever wondered how CGLIB works its magic when a @Configuration
class initializes? Here's your answer in code and... well, mostly code. It uses this wonderous spell called CGLIB to enchant @Bean
methods into faithfull followers of singleton laws. Notice, no static methods. Sorry, folks!
Watch your step: advanced patterns
Beware of the dragon...oops! Initialization logic might need a new instance. Don't fiddle with the dragon. Instead, inject away or use getBean for prototype-scoped beans.
Also, if you're murmuring the @Bean
methods of a class, be warned. Spring hears you and keeps tabs. But if you call the same @Bean
from outside the class, Spring won't recite that same singleton chant unless you've invoked it from the application context.
Spice up your configuration
You're allowed to use protected, private, and package-visible @Bean
methods if you need to. Spring won't object. Although public methods are easier to read and thus recommended.
Proceed with caution when using reflection inside @Bean
methods. JVM security might have some words with you later on proxying.
And finally, knowing the ins and outs of singleton scope and the application of @Bean
lets you exploit design patterns and write code that's cleaner, more maintainable, and well, worth bragging about!
Was this article helpful?