Sandro
Sandro

Reputation: 1276

How to programmatically determine the scope of a bean

I am trying to find out the scope of a bean by its name.

What I found so far is:

BeanFactory#isPrototype(String name)
           #isSingleton(String name)

In my case I want to find out if the bean is in request scope. There are some internal methods in Spring framework that I could use, but I am wondering if there is a "proper" way of doing it.

Upvotes: 7

Views: 2059

Answers (2)

SpaceTrucker
SpaceTrucker

Reputation: 13556

The following solution will work for instances of ConfigurableApplicationContext:

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.ConfigurableApplicationContext;

public String getScope(ConfigurableApplicationContext context, String sourceBean) {
    BeanDefinition beanDefinition = context.getBeanFactory().getMergedBeanDefinition(sourceBean);
    return beanDefinition.getScope();
}

By consulting the BeanDefinitions, this solution will also work for custom bean scopes.

Upvotes: 2

AlexR
AlexR

Reputation: 115378

Good question.

There is no method isRequst() in BeanFactory because request scope is relevant for web only.

I've just tried to find the way to do this and failed. So, I can suggest you a work-around that will work if you are using annotations. When you get bean instance say bean.getClass().getAnnotation(Scope.class). If this returns Scope call value().

This is not "scientific" method, but hopefully good enough for you.

EDIT

Other approach is the following. The request scope beans are stored in request attribute. I do not remember its name now but you can easily find it yourself, just examine your request in debugger. Then check that reference to your bean is there. This method is probably better but requires some efforts to investigate the request attribute and the data structure used by Spring framework.

Upvotes: 5

Related Questions