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

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

问题描述

我们的应用需要支持多租户.每个登上的客户可能会覆盖 1 个或多个 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 文件,并将其导入到特定于客户端的 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".

我发现处理这个问题的最干净的方法是使用 新的 @Bean-Spring 3 中引入的语法.不是将 bean 定义为 XML,而是在 Java 中定义它们.因此,您的核心 bean 将定义在一个 @Bean 注释类中,并且您的客户端配置将对其进行子类化,并覆盖适当的 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天全站免登陆