We have an application which is deployed 120 times with slightly different configurations for each. We would like the configuration to be stored in the database for auditing and managemen开发者_C百科t purposes.
How can you instantiate Spring beans directly from the database without using XML?
Thanks
You can't have zero XML config (unless you use JavaConfig, which doesn't make things different in your case) . You can externalize some of it to the database, and use a custom PropertyPlaceholderConfigurer
. See this article on how to achieve this.
@Bozho's suggestion is almost certainly the most practical solution, especially if the differences between the deployments is minimal and can be expressed via simple scalar properties.
The alternative is to write your own BeanFactory
implementation. This is a non-trivial exercise, and you want to be sure that it's what you need. A good starting point would be to look at the source for XmlBeanFactory
, and then write your own (DatabaseBeanFactory
, perhaps) which does something similar, but fetching the bean definitions from the database, rather than from local XML files.
It's going to be quite a lot of extra work, though.
There are some options which are simplier than skaffman's suggestion:
If your configuration is stored in the database in XML form, you can implement a custom resource fetching strategy by overriding
AbstractApplicationContext.getResource()
, so that you can load XML configs from the database. See here for some sample code. Using this approach you can also generate XML config on the fly.If your configuration is stored in the "disassembled" form, you can build
BeanDefinition
s and add them to theBeanDefinitionRegistry
during initialization of the context using one of the following approaches:- Implement a namespace extension
- Implement a
BeanFactoryPostProcessor
(you will need to downcastConfigurableListableBeanFactory
toBeanDefinitionRegistry
, which work for most of application contexts types) - Since Spring 3.0.1 the previous approach was rectified by introduction of
BeanDefinitionRegistryPostProcessor
In case of Web Application:
Write custom ServletContextListener implementation that populates Properties instance with the database values on application startup and passes it to the Spring's PropertyPlaceholderConfigurer. See this post for complete working example: http://blog.javaforge.net/post/31720600427/configuring-spring-based-web-application-from-database
精彩评论