tags:

views:

189

answers:

1

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!

+7  A: 

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

void setBeanName(String name)
David Rabinowitz
Thank you! Exactly what I was looking for.
Dan
It's a bit of a shame that Spring doesn't provide an annotation for this that could get the name injected directly into the bean's field without needing the interface and public setter. Hah well.
skaffman
@skaffman - you always impress me with your easy knowledge of Spring. I seek out your answers.
duffymo
@skaffmann - I think this is due to the fact, that no one of the Spring authors recommends a class to be dependent of the bean name as this typically leads to direct acces via the ApplicationContext. And this is pretty much the opposite of what DI is. If you code a small spring extension, you typically don't bother if there is one more (technical) method.
Oliver Gierke
I wanted this because each instance has a name parameter that I need for printing out statistics and since i had to set the bean name anyway, I wanted to be able to just set one. This lets me do that (and the name in Java code is not used to access Spring). I can see where this may introduce problems if the name is used to access the application context.
Dan