How to check for Request Scope availability in Spring?

元气小坏坏 提交于 2019-12-21 07:30:07

问题


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!


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/29380888/how-to-check-for-request-scope-availability-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!