Java 如何对从控制器返回的对象禁用spring销毁回调
编辑:这原来是我的配置中的其他内容 每当我从rest控制器返回一个具有可推断销毁方法的对象时,返回的对象就会关闭,是否可以禁用此功能 例如,如果我有这样一个对象:Java 如何对从控制器返回的对象禁用spring销毁回调,java,spring,spring-mvc,Java,Spring,Spring Mvc,编辑:这原来是我的配置中的其他内容 每当我从rest控制器返回一个具有可推断销毁方法的对象时,返回的对象就会关闭,是否可以禁用此功能 例如,如果我有这样一个对象: public class MyObject implements AutoCloseable { // Some json private @JsonValue String foo = "hello world"; public void close () throws Exception { System.
public class MyObject implements AutoCloseable {
// Some json
private @JsonValue String foo = "hello world";
public void close () throws Exception {
System.out.println ("close()");
new Throwable ("STACK TRACE").printStackTrace (System.out);
}
}
@Controller
public class MyController {
private Map<String, MyObject> objects = new HashMap<> ();
@PostConstruct
private void populate () {
objects.put ("one", new MyObject ());
objects.put ("two", new MyObject ());
}
@RequestMapping ("/hello/{id}")
@ResponseBody
public MyObject test (@PathVariable ("id") String id) {
return objects.get (id);
}
}
还有这样一个控制器:
public class MyObject implements AutoCloseable {
// Some json
private @JsonValue String foo = "hello world";
public void close () throws Exception {
System.out.println ("close()");
new Throwable ("STACK TRACE").printStackTrace (System.out);
}
}
@Controller
public class MyController {
private Map<String, MyObject> objects = new HashMap<> ();
@PostConstruct
private void populate () {
objects.put ("one", new MyObject ());
objects.put ("two", new MyObject ());
}
@RequestMapping ("/hello/{id}")
@ResponseBody
public MyObject test (@PathVariable ("id") String id) {
return objects.get (id);
}
}
当您有
@ResponseBody
带注释的处理程序方法时,Spring使用RequestResponseBodyMethodProcessor
来处理返回的值
这是在servleinvaccablehandler方法#invokeAndHandler(..)
中完成的,该方法就是这样实现的
public final void invokeAndHandle(ServletWebRequest webRequest,
ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception {
Object returnValue = invokeForRequest(webRequest, mavContainer, providedArgs);
setResponseStatus(webRequest);
if (returnValue == null) {
if (isRequestNotModified(webRequest) || hasResponseStatus() || mavContainer.isRequestHandled()) {
mavContainer.setRequestHandled(true);
return;
}
}
else if (StringUtils.hasText(this.responseReason)) {
mavContainer.setRequestHandled(true);
return;
}
mavContainer.setRequestHandled(false);
try {
this.returnValueHandlers.handleReturnValue(returnValue, getReturnValueType(returnValue), mavContainer, webRequest);
}
catch (Exception ex) {
if (logger.isTraceEnabled()) {
logger.trace(getReturnValueHandlingErrorMessage("Error handling return value", returnValue), ex);
}
throw ex;
}
}
在哪里
this.returnValueHandlers.handleReturnValue(returnValue, getReturnValueType(returnValue), mavContainer, webRequest);
委托给RequestResponseBodyMethodProcessor
。这里的任何内容都不会对返回值调用close()
默认情况下,您所描述的内容是不可能的。您的配置中必须有其他内容。您能给我们看一下堆栈跟踪吗?您的堆栈跟踪似乎与您发布的代码无关。你的
清理方法在哪里?你是对的,这是我配置中的另一种方法,对运行环境感到抱歉没有问题,很高兴你找到了答案。这就是我们来这里的目的。