覆盖 java 配置中的 bean 定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23547482/
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-08-13 23:47:59  来源:igfitidea点击:

Override bean definition in java config

javaspring

提问by maks

I have a configuartion class

我有一个配置类

@Configuration
public class FooConfig{
  @Bean
  public FooService fooService() { ... }
  @Bean
  public AbcService abcService() { ... }
}

That class is defined in a lib that I can't change. I have a project where FooServiceis used in many places. In my project I have another configuration class

该类是在我无法更改的库中定义的。我有一个FooService在很多地方使用的项目。在我的项目中,我有另一个配置类

@Configuration
@Import({
  FooConfig.class,

})
public class BarConfig{
  @Autowired AbcService abc;
  ...    
}

AbcServiceis used here because there are services which depends on that service and that services are declared in BarConfig. However, FooServiceis not used here(it is used only in controllers)

AbcService在这里使用是因为存在依赖于该服务的服务并且该服务在BarConfig. 但是,FooService这里不使用(仅在控制器中使用)

I need to change the implementation of FooService. Can I define new FooServicebean in BarConfig? Will it override already present definition which is imported via FooConfig?

我需要更改FooService. 我可以FooService在 中定义新beanBarConfig吗?它会覆盖通过 导入的已经存在的定义FooConfig吗?

回答by Centonni

You can redefine the same bean name multiple times, the spring container will take the last bean definition processed for a given name to be the one that wins. In your case, as the core project that contains the configuration you can't change does not depend on any of the beans you define in your project, it will work fine if you redefine the FooService bean.there was lot of answers about how to override bean defintions before, you can have a look to have more informations.

您可以多次重新定义相同的 bean 名称,spring 容器会将为给定名称处理的最后一个 bean 定义作为获胜的 bean 定义。在您的情况下,由于包含您无法更改的配置的核心项目不依赖于您在项目中定义的任何 bean,如果您重新定义FooService bean.有很多关于如何覆盖 bean 定义的答案,它将正常工作之前,你可以看看有更多的信息。