Reputation: 6006
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
?
Upvotes: 20
Views: 50546
Reputation: 402
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.
Upvotes: 17