Chapter 5. Naming strategy

In all the examples so far, the bean resulting from the method invocation, carried the method name:

@Configuration
public class ColoursConfiguration {
  // create a bean with name 'blue'
  @Bean
  public Color blue() {
    ...
  }
  ...
}
// dependency lookup for the blue colour
applicationContext.getBean("blue");

In some cases, this naming scheme is not suitable as methods with the same name, from different classes will override each other definitions. To customize the behavior, one can implement BeanNamingStrategy interface to provide its own naming generation strategy.

However, before writing your own code, take a look at the options provided by the default implementation: MethodNameStrategy.

 <!-- Java Configuration post processor -->
 <bean class="org.springframework.config.java.process.ConfigurationPostProcessor">
    <property name="namingStrategy">
       <bean class="org.springframework.config.java.naming.MethodNameStrategy">
          <property name="prefix" value="CLASS"/>
       </bean>
    </property>
 </bean>

With this configuration, the bean creation method enclosing class will be appended to the name:

// dependency lookup for the blue colour using the new naming scheme
applicationContext.getBean("ColoursConfiguration.blue");