[英]How to check for Request Scope availability in Spring?
我正在嘗試設置一些代碼,如果spring的請求范圍可用,它將以一種方式運行,如果所述范圍不可用則采用另一種方式。
有問題的應用程序是一個Web應用程序,但有一些JMX觸發器和計划任務(即Quartz)也會觸發調用。
例如
/**
* 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
}
}
}
假設myRequestScopedBean
是請求作用域。
我知道這可以通過try
- catch
調用myRequestScopedBean
,例如:
/**
* 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
}
}
}
但這看起來真的很笨重,所以我想知道是否有人知道一種優雅的Spring方式來詢問某些東西,看看請求范圍的bean是否可用。
非常感謝!
您可以使用此處描述的if檢查
if (RequestContextHolder.getRequestAttributes() != null)
// request thread
而不是捕捉異常。 有時這看起來像最簡單的解決方案。
您可以注入Provider<MyRequestScopedBean>
並在調用get
方法時捕獲異常,但您應該重新考慮您的設計。 如果你對它有強烈的感覺,你可能應該有兩個具有不同限定符的bean
編輯
退一步講,如果你正在使用Java配置, @Scope("prototype")
的@Bean
方法,讓你決定在那里,你可以通過獲得請求上下文句柄RequestContextHolder
(如果可用)。 但我強烈建議你重新考慮你的設計
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.