简体   繁体   English

如何以编程方式确定bean的范围

[英]How to programmatically determine the scope of a bean

I am trying to find out the scope of a bean by its name. 我试图通过其名称找出bean的范围。

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. 在我的情况下,我想知道bean是否在请求范围内。 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. 我可以使用Spring框架中的一些内部方法,但我想知道是否有一种“正确”的方法。

Good question. 好问题。

There is no method isRequst() in BeanFactory because request scope is relevant for web only. BeanFactory没有isRequst()方法,因为请求范围仅与Web相关。

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) . 当你获得bean实例时说bean.getClass().getAnnotation(Scope.class) If this returns Scope call value() . 如果这返回Scope调用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. 请求范围bean存储在请求属性中。 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. 然后检查对bean的引用是否存在。 This method is probably better but requires some efforts to investigate the request attribute and the data structure used by Spring framework. 这种方法可能更好,但需要一些努力来研究Spring框架使用的请求属性和数据结构。

The following solution will work for instances of ConfigurableApplicationContext : 以下解决方案适用于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 BeanDefinition s, this solution will also work for custom bean scopes. 通过查阅BeanDefinition ,该解决方案也适用于自定义bean范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM