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.
问题:
回答1:
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.