Search code examples
springspring-el

Inject the value of xml id into spring bean


I'm curious if anyone knows a quick way to accomplish my goal. I want to inject the value of the id into a String on my spring bean.

This is what I want in a nutshell:

<bean id="matsientst" class="com.matt.Matt"/>

public class Matt {
    @Value("#id")
    String id;
}

The reason I need this is that we have a lot of objects that are configured in our spring xml that I also need to manage in the DB. The Spring id is a convenient key that I can use. I don't want to have to inject all my objects since I have them all abstracted I could elegantly have the Abstract class set the ID. That is, if this works. Thanks -matt


Solution

  • Just implement BeanNameAware, and Spring will supply the id or name attribute (whichever one you used), e.g.

    public class Matt implements BeanNameAware {
        private String id;
    
        public void setName(String beanName) {
           this.id = beanName;
        }
    }