Taylor
Taylor

Reputation: 4086

How to check for Request Scope availability in 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.

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!

Upvotes: 23

Views: 12529

Answers (2)

Sergey Shcherbakov
Sergey Shcherbakov

Reputation: 4778

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.

Upvotes: 31

Lev Kuznetsov
Lev Kuznetsov

Reputation: 3728

You can inject a Provider<MyRequestScopedBean> and catch the exception when calling the get method but you should rethink your design. If you feel strongly about it you should probably have two beans with different qualifier

Edit

On second thought, if you are using java configuration, @Scope("prototype") your @Bean method and make your decision there, you can get a handle on request context via RequestContextHolder if available. But I strongly recommend you rethink your design

Upvotes: 2

Related Questions