覆盖在上下文中的父上下文中定义的bean [英] Overriding the bean defined in parent context in a child context

查看:153
本文介绍了覆盖在上下文中的父上下文中定义的bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的应用程序需要支持多租户。每个登机客户可能潜在地覆盖在核心平台级别定义的一个或多个bean或一些bean的属性(通用代码/定义)。我想知道什么是最好的方法来解决这个问题。

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.

推荐答案

Spring允许你多次重新定义相同的bean名称,将给定名称处理的最后一个bean定义为获胜的bean定义。因此,例如,您可以有一个XML文件来定义您的核心bean,并将其导入到客户端特定的XML文件中,这也重新定义了一些这些bean。但是有一点是脆弱的,因为没有任何机制来专门说这个bean定义是一个覆盖。

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".

我发现最简单的方法是使用新的<$在Spring 3中引入的c $ c> @Bean -syntax 。您可以使用Java定义它们,而不是将bean定义为XML。因此,您的核心bean将在一个 @Bean -annotated类中定义,您的客户端配置将对其进行子类化,并覆盖相应的bean。这允许您使用标准java @Override 注释,明确指出给定的bean定义被覆盖。

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.

这篇关于覆盖在上下文中的父上下文中定义的bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆