How to check availability of request in Spring?

I'm trying to set up a code that will behave in one way if the spring request area is available, and another way if the specified area is not available.

This application is a web application, but there are some JMX triggers and scheduled tasks (i.e. quartz) that also trigger calls.

eg.

/**
 * 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 it myRequestScopedBeanhas a request scope.

I know that this can be done with try- catcharound the call myRequestScopedBean, for example:

/**
 * 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 this seems really awkward, so I wonder if anyone knows about the elegant spring way of polling something to see if beans are available with the request.

Many thanks!

+4
2

if

SPRING -

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

. .

+5

Provider<MyRequestScopedBean> get, . , beans

, java-, @Scope("prototype") @Bean , RequestContextHolder, . .

+1

All Articles