title: Overriding beans in Java-based spring configuration hierarchy
body: <p>Let's assume we have an application that can be customized for some customers. The application is using Java-based spring configuration (a.k.a. Java config) for dependency injection. The application consists of modules and their submodules. Each module and submodule has its own <code>@Configuration</code> class which is imported by parent configuration using <code>@Import</code>. This creates the following hierarchy:</p>
  
  <pre><code>                MainConfig
            ----------+----------------   ....
            |                         |
      ModuleAConfig               ModuleBConfig
        |--------------------|
        |                    |
      SubModuleA1Config    SubModuleA2Config
  </code></pre>
  
  <p>For example <code>ModuleAConfig</code> looks like this:</p>
  
  <pre><code>@Configuration
  @Import({SubModuleA1Config.class, SubModuleA2Config.class})
  public class ModuleAConfig {
      // some module level beans
  }
  </code></pre>
  
  <p>Let's say that <code>SubModuleA1Config</code> defines bean <code>someBean</code> of type SomeBean:</p>
  
  <pre><code>@Configuration
  public class SubModuleA1Config {
      @Bean
      public SomeBean someBean() { return new SomeBean(); }
  }
  </code></pre>
  
  <p>Now I want to customize the application for Customer1 (C1) - I want to use <code>C1SomeBean</code> (extending <code>SomeBean</code>) instead of <code>SomeBean</code> as <code>someBean</code>. </p>
  
  <p>How can I achieve this with minimum duplication?</p>
  
  <p>One of my ideas was to prepare alternative hierarchy with <code>C1Config</code> inheriting from <code>MainConfig</code>, <code>C1ModuleAConfig</code> from <code>ModuleAConfig</code> and <code>C1SubModuleA1Config</code> from <code>SubModuleA1Config</code>. <code>C1SubModuleA1Config</code> would override <code>someBean()</code> method returning <code>C1SomeBean</code>. Unfortunately with Spring 4.0.6 I get something like:</p>
  
  <pre><code>   Overriding bean definition for bean 'someBean': replacing [someBean defined in class C1SubmoduleA1Config] with [someBean defined in class SubModuleA1Config]
  </code></pre>
  
  <p>and indeed <code>SomeBean</code> class is returned from context instead of <code>C1SomeBean</code>. This is clearly not what I want.</p>