Does anyone know if there is a way to hook into the Spring container so that when it has completed initialising, I can then cause some code to start running?
Basically I need the database state to be checked when the app is started up and cannot do it in a bean at startup as I need the persistance tier to have been initialised.
Anyone any ideas of how I can get around this?
I am using Spring 3 and it is running from within Tomcat.
There are three approaches. Two of which I recommend.
1) @PostConstruct. Annotate the method you want to run with this annotation and include <context:annotation-driven> or <context:component-scan/> to tell Spring you are using this annotation
2) the <bean> tag has an attribute called init-method, set it to the name of the method of the bean you want to run.
I won't even mention the third approach.
Anyway, the method you tell Spring to run will get called after all the objects have been initialized/instantiated, and all it dependencies and properties are set. Just like what you need.
Thanks for your reply. I had already tried with the @PostConstruct annotation, but for some reason I was getting transaction manager exceptions when I was trying to run DAO code (perhaps the transaction manager hadn't started up). Anyway I think we resolved the issue, we created a class that implements the ApplicationListener interface and looked for a ContextRefreshed Event and this seems to work.
Thanks for your reply. I had already tried with the @PostConstruct annotation, but for some reason I was getting transaction manager exceptions when I was trying to run DAO code (perhaps the transaction manager hadn't started up). Anyway I think we resolved the issue, we created a class that implements the ApplicationListener interface and looked for a ContextRefreshed Event and this seems to work.
Thanks for your reply though.
Sean
Yes that does work. The only issue with it is now you have a class that it coupled with Spring. Meaning that class won't work outside of Spring, you will always have to have the Spring jars in your classpath at compile and runtime.
Whereas with @PostContruct or init-method, your code can stay POJO.
What were the transaction exceptions you got. Spring will not call your @PostConstruct method till all beans are instantiated, dependencies injected and properties set, so it must have been something else.