simonC simonC - 12 days ago 4
Java Question

How to properly overload Spring bean configuration

I'm having two spring(4.2) java configurations, one in a base module and one in a client specific module:

@Configuration
public class BaseConfig {

@Bean
public A getA() {
return new A("aaa");
}

}

@Configuration
public class ClientConfig {

@Bean
public A getA() {
return new A("bbbb");
}

}


During the app load there is always
BaseConfig.getA()
called, how can I ovverride the base bean factory configuration to have some client specific stuff?

Answer

Personally I would NEVER override a bean in spring! I have seen people spend too much time debugging issues related to this. For the same reason I would never use @Primary.

In this case I would have 3 contexts

  1. Context that contains beans unique to the parent context
  2. Context that contains beans unique to the child context
  3. Abstract context that contains all shared beans.

This way you will specify the 2 contexts to load. This could be done programatically, or using profiles. Potentially you will need more contexts, because you probably want some of your beans to be different in tests.

Comments