Thiago Sayão
Thiago Sayão

Reputation: 2357

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?

Upvotes: 0

Views: 868

Answers (1)

Michał Mielec
Michał Mielec

Reputation: 1651

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();
    }

Upvotes: 1

Related Questions