Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding the bean defined in parent context in a child context

Tags:

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.

like image 804
Aravind Yarram Avatar asked Nov 22 '10 20:11

Aravind Yarram


People also ask

Are beans defined in parent context visible to child contexts?

Beans from parent context are visible in child context but not vice-versa. That way, a child context can use beans and configuration from parent context and override only what's necessary. Example of that can be a security defined in parent context and used/overridden in child contexts.

What is bean overriding?

Thus, bean overriding is a default behavior that happens when we define a bean within an ApplicationContext which has the same name as another bean. It works by simply replacing the former bean in case of a name conflict.

What will a child bean definition inherited from parent definition?

A child bean definition is a bean definition that inherits configuration data from a parent definition. It is then able to override some values, or add others, as needed. Using parent and child bean definitions can potentially save a lot of typing. Effectively, this is a form of templating.

What is parent in bean definition?

You can define a parent bean definition as a template and other child beans can inherit the required configuration from the parent bean. When you use XML-based configuration metadata, you indicate a child bean definition by using the parent attribute, specifying the parent bean as the value of this attribute.


1 Answers

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.

like image 154
skaffman Avatar answered Oct 06 '22 03:10

skaffman