19

I have a configuration 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 FooService is used in many places. In my project I have another configuration class

@Configuration
@Import({
  FooConfig.class,
   
})
public class BarConfig{
  @Autowired AbcService abc;
  ...    
}

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

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

phoenixSid
  • 447
  • 1
  • 8
  • 22
maks
  • 5,911
  • 17
  • 79
  • 123

1 Answers1

16

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.

Community
  • 1
  • 1
Centonni
  • 372
  • 1
  • 5
  • I can't change `FooConfig`. What is the id of a `FooService` bean defined there? It is not specified explicitly. If I know the id, I will be able to override it as you described – maks May 13 '14 at 10:54
  • 1
    With java based config,the method name annotated with `@Bean` works as bean ID. In your case `fooService` will assume the role of id. – Centonni May 13 '14 at 12:20