user21037
user21037

Reputation:

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

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!

Upvotes: 36

Views: 20580

Answers (1)

David Rabinowitz
David Rabinowitz

Reputation: 30448

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

void setBeanName(String name)

Upvotes: 55

Related Questions