spring 在子上下文中覆盖父上下文中定义的 bean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4249978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 04:13:25  来源:igfitidea点击:

Overriding the bean defined in parent context in a child context

springarchitecturejakarta-eemulti-tenant

提问by Aravind Yarram

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 个或多个 bean 或在核心平台级别定义的 bean 的某些属性(公共代码/定义)。我想知道处理这个问题的最佳方法是什么。

回答by skaffman

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 允许您多次重新定义相同的 bean 名称,并将为给定名称处理的最后一个 bean 定义作为获胜者。例如,您可以有一个定义核心 bean 的 XML 文件,并将其导入到特定于客户端的 XML 文件中,该文件还会重新定义其中一些 bean。但是,它有点脆弱,因为没有机制专门说“这个 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 @Overrideannotations, explicitly indicating that a given bean definition is being overridden.

我发现处理这个问题的最干净的方法是使用Spring 3 中引入@Bean-syntax。不是将 bean 定义为 XML,而是在 Java 中定义它们。因此,您的核心 bean 将在一个带@Bean注释的类中定义,您的客户端配置将子类化该类,并覆盖适当的 bean。这允许您使用标准的 java@Override注释,明确指示给定的 bean 定义正在被覆盖。