Spring Bean names

Spring bean names are straightforward, except for cases where names are not explicitly specified. To start with, Spring bean names for an xml based bean definition is specified this way:
 
 
 
 
 
 
 
 

<bean name='sampleService1' class='mvcsample.beanname.SampleService'>
 <constructor-arg>
  <bean class='mvcsample.beanname.SampleDao'></bean>
 </constructor-arg>
</bean>

For a Java @Configuration based bean definition, the method name of the @Bean annotated method becomes the bean name:

@Configuration
@ComponentScan(basePackages='mvcsample.beanname')
public static class SpringConfig{

 @Bean
 public SampleService sampleService(){
  return new SampleService(sampleDao());
 }

 @Bean
 public SampleDao sampleDao(){
  return new SampleDao();
 }

}

and for Stereotype annotation(@Component, @Service, @Repository etc) based beans, the value field indicates the bean name:

@Repository('aSampleDao')
public class SampleDao {
    ...
}

@Service('aSampleService')
public class SampleService {
    ...
}

Now, what happens for cases where the bean name is not specified.

XML Based Bean Configuration Case:

For an xml based configuration, a case where the bean name is typically not specified are for beans which can act on the entire bean factory – say for eg, to define a BeanPostProcessor or a BeanFactoryPostProcessor For eg. consider the following dummy BeanPostProcessor that just grabs all the bean names from bean factory:

public class BeanNameScanningBeanPostProcessor implements BeanPostProcessor{
 private List<String> beanNames = new ArrayList<>();
 @Override
 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  return bean;
 }

 @Override
 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
  beanNames.add(beanName);
  return bean;
 }

 public List<String> getBeanNames(){
  return this.beanNames;
 }
}

It would typically be defined in an xml bean configuration this way:

<bean class='mvcsample.beanname.BeanNameScanningBeanPostProcessor'/>

A second case with xml based configuration where a name is typically not specified is with inner beans, for eg. defined this way:

<bean class='mvcsample.beanname.SampleService'>
 <constructor-arg>
  <bean class='mvcsample.beanname.SampleDao'></bean>
 </constructor-arg>
</bean>

The bean names for these cases is handled by a component called the BeanNameGenerator. For the case of a top level bean the name typically ends up being the package qualified class name along with a count of the instances, this way:

mvcsample.beanname.BeanNameScanningBeanPostProcessor#0

For the case of an inner bean, since it exists only in the scope of its containing bean, the name is not that relevant, however internally it does get a name based on the hex hash code of the bean definition for eg, ‘mvcsample.beanname.SampleDao#1881ee8b’

Java Based @Configuration Case:

For java based @Configuration on the other hand it is not possible to specify a bean without a name, the bean name is the method name.

Annotation based Configuration

For stereotype annotation based bean, if the name is not explicitly specified with the value field of stereotype annotations, then the name is again generated by AnnotationBeanNameGenerator which is an implementation of the BeanNameGenerator strategy interface, the names generated is simply the short name of the class, for eg from the javadoc for AnnotationBeanNameGenerator – bean name for com.xyz.FooServiceImpl becomes fooServiceImpl.

Conclusion:

So to finally conclude, if bean names are relevant to you in some way(for eg to disambiguate between multiple bean instances of same type), then it is best to be explicit about the names, otherwise depend on Spring to generate the bean names for you. In some cases, for eg. with Spring-data project it is possible to specify custom behavior for repositories as a separate bean and
Spring-data by default uses Spring naming conventions to find the custom implementation and understanding how bean names are generated helps.
 

Reference: Spring Bean names from our JCG partner Biju Kunjummen at the all and sundry blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


7 × three =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books