Spring Boot项目如何将配置属性注入@ResponseStatus注解
问题原因
Java注解的属性值必须是编译期常量,且Spring默认的ResponseStatusExceptionResolver不会对@ResponseStatus的reason字段做配置占位符解析,因此你直接在注解里写${message.custom.notFound}会原样输出,不会读取properties里的配置值。
可行解决方案
方案1:全局异常处理器(推荐)
该方案灵活性最高,还支持自定义错误返回结构,适配多数业务场景:
- 调整自定义异常的
@ResponseStatus配置,移除reason属性:
@ResponseStatus(code = HttpStatus.NOT_FOUND) // 注意:原类名MyCustomAnnotation不符合异常类命名规范,建议调整为MyCustomNotFoundException等符合语义的名称 public class MyCustomException extends RuntimeException { }
- 实现
@RestControllerAdvice全局异常处理器,注入配置值后处理该异常:
@RestControllerAdvice public class GlobalExceptionHandler { // 注入配置文件中的提示信息 @Value("${message.custom.notFound}") private String notFoundMsg; @ExceptionHandler(MyCustomException.class) public ResponseEntity<Map<String, Object>> handleCustomNotFound(MyCustomException e) { Map<String, Object> errorBody = new HashMap<>(); errorBody.put("code", HttpStatus.NOT_FOUND.value()); errorBody.put("message", notFoundMsg); // 可根据业务需求扩展其他字段 return new ResponseEntity<>(errorBody, HttpStatus.NOT_FOUND); } }
方案2:自定义ResponseStatus异常解析器
如果你希望保留原有@ResponseStatus加reason的写法,可以自定义异常解析器手动做占位符解析:
@Component public class PlaceholderSupportResponseStatusResolver extends ResponseStatusExceptionResolver { private final Environment environment; public PlaceholderSupportResponseStatusResolver(Environment environment) { this.environment = environment; // 设置最高优先级,避免被其他异常解析器覆盖 setOrder(Ordered.HIGHEST_PRECEDENCE); } @Override protected String resolveReason(ResponseStatus responseStatus) { // 手动解析reason中的配置占位符 return environment.resolvePlaceholders(responseStatus.reason()); } }
注意:该方案需要确保没有其他优先级更高的异常处理器提前处理了你的自定义异常,否则解析逻辑不会生效。
内容的提问来源于stack exchange,提问作者Devidb
相关产品推荐
相关产品推荐

