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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With