Spring 如何向错误模板模型添加属性?

Spring 如何向错误模板模型添加属性?,spring,spring-boot,spring-mvc,thymeleaf,Spring,Spring Boot,Spring Mvc,Thymeleaf,当Spring返回404响应时,将返回一个错误视图,如//error/404.html。在我的例子中,这是一个Thymeleaf模板 我想为所有错误模板的模型添加一个属性“X”错误/4xx,错误/404,错误/5xx,等等 在@Controller中,我将使用@modeldattribute注释向每个@RequestMapping添加一个属性,但是这对于异常处理视图是不可能的: 模型增强方法(用于向模型添加附加数据) 用@modeldattribute注释。请注意,这些属性不是 可用于异常处理视

当Spring返回404响应时,将返回一个错误视图,如
//error/404.html
。在我的例子中,这是一个Thymeleaf模板

我想为所有错误模板的模型添加一个属性“X”<代码>错误/4xx,
错误/404
错误/5xx
,等等

@Controller
中,我将使用
@modeldattribute
注释向每个
@RequestMapping
添加一个属性,但是这对于异常处理视图是不可能的:

模型增强方法(用于向模型添加附加数据) 用@modeldattribute注释。请注意,这些属性不是 可用于异常处理视图


以下是我最终做的事情:

@Component
public class AdditionalErrorAttributes extends DefaultErrorAttributes {

    private final SomeService service;

    public AdditionalErrorAttributes(SomeService service) {
        this.service = service;
    }

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace);

        errorAttributes.put("someAttribute", service.getAttribute());

        return errorAttributes;
    }
}
@组件
公共类AdditionalErrorAttributes扩展了DefaultErrorAttributes{
私人最终服务;
公共附加ErrorAttributes(SomeService服务){
服务=服务;
}
@凌驾
公共映射getErrorAttributes(WebRequest WebRequest,布尔includeStackTrace){
Map errorAttributes=super.getErrorAttributes(webRequest,includeStackTrace);
errorAttributes.put(“someAttribute”,service.getAttribute());
返回错误属性;
}
}

如果可以实现,那就很有趣;尽管如此,根据你所引用的,我还是怀疑它。