gpt4 book ai didi

java - 如何在 Spring 中检查请求范围的可用性?

转载 作者:IT老高 更新时间:2023-10-28 13:46:53 29 4
gpt4 key购买 nike

我正在尝试设置一些代码,如果 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 是请求范围的。

我知道这可以通过围绕 myRequestScopedBean 调用的 try-catch 来完成,例如:

/**
* 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 检查

SPRING - Get current scope

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

而不是捕获异常。有时这看起来是最简单的解决方案。

关于java - 如何在 Spring 中检查请求范围的可用性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29380888/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com