How to check for Request Scope availability in Spring?

前端 未结 2 1428
醉梦人生
醉梦人生 2021-02-19 08:20

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 quest

相关标签:
2条回答
  • 2021-02-19 08:45

    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.

    0 讨论(0)
  • 2021-02-19 08:47

    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

    0 讨论(0)
提交回复
热议问题