Load spring context in phases

2019-07-18 15:26发布

问题:

This is one of those strange questions where people would ask - why?

So I will start with why I would like to do this and then go into the issue. I would like to have more control over how the spring context is loaded. For example, I do not want to load the domain and web-api at the same time. That would make the resources available before their dependencies are ready. There might also be that I need to check the state of something before I can continue this process. So to say, there will be sequential order between modules/contexts. Maybe not just booting but also in shutdown.

So the issue is that I can't find any information on how to load the domain-context, then when that is finished I would check the state and lastly load the api-context. I would like to do all of this from java-code as I need to control the flow of the start up. I have basics working with SpringServlet loading the web-context. What I have not found any information on is if it is possible to load a context, wait and load another context that refers to the first one.

It might be good to know that I am not using JavaEE nor a container. I am only using embeddded Jetty with servlet and spring. So is there a way this can be done?

回答1:

I'd suggest to consider following:

  • Read SmartLifeCycle and Phased for extension points on the order of application context life cycle management. The idea is that you have your top-level important beans implement the interfaces such that the standard application context initialization will be also handled to those beans in the order that you customize.
  • Break your application context XML files into smaller pieces. Use <import /> in the ones that depend on a higher/lower context.
  • Use depends-on attribute on your mission critical beans to ensure the dependencies.
  • Use InitializingBean on the ones that you need to make sure a dependency is satisfied for the current bean after it's initialized.


回答2:

Consider lazy loaded beans and Lazy Proxy. So the bean will be created only on first usage ...