views:

196

answers:

2

Hi,

I am having an issue when trying to create beans from a spring Application Context inside a bean instatiated by sptring 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?

Thanks,

+4  A: 

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.

KLE
Alternatively, implement `InitializingBean` or use the `@PostConstruct` annotation.
skaffman
+2  A: 

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

denis.zhdanov