Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically determine the scope of a bean

Tags:

java

scope

spring

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.

like image 562
Sandro Avatar asked May 11 '15 09:05

Sandro


People also ask

What are the different scopes provided for a bean?

The following are the different scopes provided for a bean: Singleton: Only one instance will be created for a single bean definition per Spring IoC container and the same object will be shared for each request made for that bean. Prototype: A new instance will be created for a single bean definition every time a request is made for that bean.

How do you use prototype scope in a bean?

Prototype Scope A bean with the prototype scope will return a different instance every time it is requested from the container. It is defined by setting the value prototype to the @Scope annotation in the bean definition: We can also use a constant like we did for the singleton scope:

What is the default scope of a bean in Java?

By default scope of a bean is singleton. So we don’t need to declare a been as singleton explicitly. By default scope is not prototype so you have to decalre the scope of a been as prototype explicitly. Singleton scope should be used for stateless beans.

How do I set the scope of a singleton Bean?

The default scope is always singleton. However, when you need one and only one instance of a bean, you can set the scope property to singleton in the bean configuration file, as shown in the following code snippet − <!-- A bean definition with singleton scope --> <bean id = "..." class = "..."


1 Answers

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.

like image 145
AlexR Avatar answered Oct 13 '22 00:10

AlexR