如何检查Spring中的请求范围可用性? [英] How to check for Request Scope availability in Spring?

查看:189
本文介绍了如何检查Spring中的请求范围可用性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to setup some code that will behave one way if spring's request scope is available, and another way if said scope is not available.

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

The application in question is a web app, but there are some JMX triggers and scheduled tasks (i.e. Quartz) that also trigger invocations.

例如

/**
 * 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 是请求作用域。

我知道这可以做到使用尝试 - catch 围绕 myRequestScopedBean 的调用,例如:

I know this can be done with a try-catch around the invocation of myRequestScopedBean, 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(){
        try{
            myRequestScopedBean.invoke();
        }catch(Exception e){
            //do something else
        }
    }
}

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

but that seems really clunky, so I'm wondering if anyone knows of an elegant Spring way to interrogate something to see if request-scoped beans are available.

非常感谢!

推荐答案

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

You can use the if check described here

SPRING - 获取当前范围

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

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

instead of catching exceptions. Sometimes that looks like the simplest solution.

这篇关于如何检查Spring中的请求范围可用性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆