如何检查Spring中的请求范围可用性?

时间:2015-04-01 00:31:58

标签: java spring spring-mvc spring-ioc

我正在尝试设置一些代码,如果spring的请求范围可用,它将以一种方式运行,如果所述范围不可用则采用另一种方式。

有问题的应用程序是一个Web应用程序,但是有一些JMX触发器和计划任务(即Quartz)也会触发调用。

E.g。

/**
 * This class is a spring-managed singleton
 */
@Named
class MySingletonBean{

    /**
     * This bean is always request scoped
     */
    @Inject
    private MyRequestScopedBean myRequestScopedBean; 

    /* can be invoked either as part of request handling
       or as part of a JMX trigger or scheduled task */
    public void someMethod(){
        if(/* check to see if request scope is available */){
            myRequestScopedBean.invoke();
        }else{
            //do something else
        }
    }
}

假设myRequestScopedBean是请求作用域。

我知道这可以通过调用try周围的catch - myRequestScopedBean来完成,例如:

/**
 * This class is a spring-managed singleton
 */
@Named
class MySingletonBean{

    /**
     * This bean is always request scoped
     */
    @Inject
    private MyRequestScopedBean myRequestScopedBean; 

    /* can be invoked either as part of request handling
       or as part of a JMX trigger or scheduled task */
    public void someMethod(){
        try{
            myRequestScopedBean.invoke();
        }catch(Exception e){
            //do something else
        }
    }
}

但这看起来很笨重,所以我想知道是否有人知道一种优雅的Spring方式来询问某些内容,看看请求范围的bean是否可用。

非常感谢!

2 个答案:

答案 0 :(得分:9)

您可以使用此处描述的if检查

SPRING - Get current scope

if (RequestContextHolder.getRequestAttributes() != null) 
    // request thread

而不是捕获异常。 有时这看起来像是最简单的解决方案。

答案 1 :(得分:1)

您可以在调用Provider<MyRequestScopedBean>方法时注入get并捕获异常,但您应该重新考虑您的设计。如果您对此感到强烈,那么您应该有两个具有不同限定符的bean

修改

第二个想法,如果你使用的是java配置,@Scope("prototype")你的@Bean方法并在那里做出决定,你可以通过RequestContextHolder获取请求上下文的句柄(如果有的话)。但我强烈建议你重新考虑你的设计