How to get the id of a bean from inside the bean in Spring?

user21037 picture user21037 · Jul 29, 2009 · Viewed 17.9k times · Source

What is the easiest way to retrieve a bean id from inside that bean (in the Java code) without using a BeanPostProcessor to set a field?

The only way I can think of is something like this using a BeanPostProcessor:

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    ((MyBean)bean).setName(beanName);
    return bean;
}

Is there a better way that doesn't require me to write an extra class or know the class of the bean in question? I tried searching through the docs and on Google, but I'm not really sure what I need to be looking for.

Thanks!

Answer

David Rabinowitz picture David Rabinowitz · Jul 29, 2009

Just implement the org.springframework.beans.factory.BeanNameAware interface and you will get it automatically. It has one method:

void setBeanName(String name)