Search code examples
springspring-ioc

how to get bean scope on spring?


I have the following class:

public class ServiceFactory {

    private ServiceFactory() {

    }

    public static <T extends XXXX> T loadService(Class<T> klass) {
        ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
        return applicationContext.getBean(klass);
    }
}

It loads beans at runtime (I have a specific reason to do it like this).

I need to check if the bean is annotated with @Scope(BeanDefinition.SCOPE_PROTOTYPE) or just enforce it to be a prototype.

How would I do this?


Solution

  • First you need to find a bean name for your class. Then you may look for BeanDefinition using that name and get scope.

    public <T> String findScope(ConfigurableApplicationContext applicationContext, Class<T> type) {
            String[] names = applicationContext.getBeanFactory().getBeanNamesForType(type);
            if(names.length != 1){
                throw new IllegalArgumentException("Could not find bean of type" + type.getCanonicalName());
            }
            return applicationContext.getBeanFactory().getBeanDefinition(names[0]).getScope();
        }