Spring Application Context available inside the constructor
-
21-09-2019 - |
Question
I am having an issue when trying to create beans from a spring Application Context inside a bean instantiated by spring using constructor arguments.
I have implemented the ApplicationContextAware
interface but it populates the context after the instance is created (obvious).
But then, if you need to get beans from the constructor, and I am talking about a variable number of objects defined at runtime, what would be the correct way to proceed?
Solution
In beans instanciated by Spring, instead of initializing it in the Constructor, initialize it in a dedicated method, marked as "init-method" for Spring.
You have about the same effect as initializing in the constructor, but you are using the correct Spring life-cycle.
OTHER TIPS
You can make the context accessible from constructor exploiting aspect-oriented programming. Spring has special support for that - @Configurable(preConstruction = true).
Feel free to read more about that at the spring reference - 6.8.1. Using AspectJ to dependency inject domain objects with Spring