Sunday, April 21, 2013

Generate BeanName using Spring AnnotationBeanNameGenerator

Developing application with Spring, sometimes require to retrieve bean name which you have either specified in @Bean annotation or bean id which is internally generated by Spring.

Spring by Default generate Bean id same as Bean class name but with first letter in small caps.
Using Spring AnnotationBeanNameGenerator class, one can achieve this using generateBeanName method.

Ex. private AnnotationBeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
String beanName = this.beanNameGenerator.generateBeanName(definition, registry); 

Here,
(1) definition is Spring BeanDefinition. BeanDefinition describes bean instance which has property values, constructor argument values any many more.

In order to retrieve BeanDefinition for bean, method resolveScopeMetadata(BeanDefinition definition) of Spring interface like ScopeMetadatResolver or AnnotationScopeMetadataResolver can be used.


Spring provide interface called AnnotatedBeanDefinition which provide awesome bean information like getMetadata() for those beans which has annotation defined.

(2) registry is of Spring BeanDefinitionRegistry.(Ex. BeanDefinitionRegistry registry)  it's basically interface for registries which holds bean Definition. It's only interface which encapsulate registries of bean Definition

After struggling hours , I finally able to make things working. Hope you find this information useful

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

No comments:

Post a Comment