Overriding the bean defined in parent context in a child context

Aravind Yarram picture Aravind Yarram · Nov 22, 2010 · Viewed 26.2k times · Source

Our app has a requirement to support multi-tenancy. Each of the boarded customer might potentially override 1 or more beans or some properties of a bean defined at the core platform level (common code/definitions). I am wondering what is the best way to handle this.

Answer

skaffman picture skaffman · Nov 22, 2010

Spring allows you to redefine the same bean name multiple times, and takes the last bean definition processed for a given name to be the one that wins. So for example, your could have an XML file defining your core beans, and import that in a client-specific XML file, which also redefines some of those beans. It's a bit fragile, though, since there's no mechanism to specifically say "this bean definition is an override".

I've found that the cleanest way to handle this is using the new @Bean-syntax introduced in Spring 3. Rather than defining beans as XML, you define them in Java. So your core beans would be defined in one @Bean-annotated class, and your client configs would subclass that, and override the appropriate beans. This allows you to use standard java @Override annotations, explicitly indicating that a given bean definition is being overridden.