How to check for Request Scope availability in Spring?

Taylor picture Taylor · Apr 1, 2015 · Viewed 7.4k times · Source

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.

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

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
        }
    }
}

Assuming myRequestScopedBean is request scoped.

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
        }
    }
}

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.

Many thanks!

Answer

Sergey Shcherbakov picture Sergey Shcherbakov · Oct 6, 2016

You can use the if check described here

SPRING - Get current scope

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

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