简体   繁体   中英

Inject property value into @ResponseStatus annotation

In my microservice Spring Boot project, I have this custom exception annotated with @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}").

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);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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