覆盖java配置中的bean定义

mak*_*aks 14 java spring

我有一个configuartion课程

@Configuration
public class FooConfig{
  @Bean
  public FooService fooService() { ... }
  @Bean
  public AbcService abcService() { ... }
}
Run Code Online (Sandbox Code Playgroud)

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

@Configuration
@Import({
  FooConfig.class,

})
public class BarConfig{
  @Autowired AbcService abc;
  ...    
}
Run Code Online (Sandbox Code Playgroud)

AbcService这里使用的是因为有些服务依赖于该服务并且声明了服务BarConfig.但是,FooService此处未使用(仅在控制器中使用)

我需要改变执行FooService.我可以定义新的FooServicebean BarConfig吗?它是否会覆盖通过导入的已存在的定义FooConfig

Cen*_*nni 11

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