简体   繁体   English

将属性值注入@ResponseStatus 注解

[英]Inject property value into @ResponseStatus annotation

In my microservice Spring Boot project, I have this custom exception annotated with @ResponseStatus :在我的微服务 Spring Boot 项目中,我使用 @ResponseStatus 注释了这个自定义异常:

@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "${message.custom.notFound}")
public class MyCustomAnnotation extends RuntimeException

and it works pretty well : when the exception is raised my controller returns the specified status (404), but the reason is not resolved (error message is "${message.custom.notFound}").它工作得很好:当引发异常时,我的控制器返回指定的状态(404),但原因没有解决(错误消息是“${message.custom.notFound}”)。

Do you know if there is a way to inject a property from a properties file into this annotation?您知道是否有办法将属性文件中的属性注入此注释中吗?

Thanks in advance提前致谢

First define message parameter in constructor :首先在构造函数中定义消息参数:

@ResponseStatus(HttpStatus.NOT_FOUND)
public class MyCustomAnnotation extends RuntimeException {
    public MyCustomAnnotation(String message) {
        super(message);
    }
}

Then use in controller service like this :然后像这样在控制器服务中使用:

@RestController
public class MainController {

 @Value($value.from.properties)
 private String value;

    @PostMapping("/api")
    public ResponseEntity send(@RequestBody requestBody) {
        throw new MyCustomAnnotation(value);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM