Get bean id from class

Viewed 48

I have the following bean :

   <bean id="slpStore"
          class="com.strategy.interceptor.SlpStoreInterceptor" >
    </bean>

I suppose only one bean exists in the spring context from the SlpStoreInterceptor.class, How can I retrieve the id of this bean which is "slpStore" if I only know the class name :SlpStoreInterceptor.class?

1 Answers

You can use the ApplicationContext.getBeanNamesForType() method:

@Component
public class BeanNames {

    private final ApplicationContext applicationContext;

    public BeanNames(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public String[] getBeanNames() {
        return applicationContext.getBeanNamesForType(SlpStoreInterceptor.class);
    }
}
Related