I have a final class Constants, which holds some final data.
@Component
public final class Constants {
public final String TOKEN;
public final String HOST;
public final String TELEGRAM;
public Constants(@Value("${myapp.bot-token}") String token,
@Value("${myapp.host}") String host) {
this.TOKEN = token;
this.HOST = host;
this.TELEGRAM = "https://api.telegram.org/bot" + TOKEN;
}
}
The problem is that, when I want to use a variable as @PostMapping
path, I faced this error:
Attribute value must be constant
@RestController
@RequestMapping
public class Controller {
private final Constants constants;
@Autowired
public Controller(Constants constants) {
this.constants = constants;
}
@PostMapping(constants.TOKEN)// Problem is here
public ResponseEntity<?> getMessage(@RequestBody String payload) {
return new ResponseEntity<HttpStatus>(HttpStatus.OK);
}
}
I’ve tried to load TOKEN
in my controller class but faced the same issue.
@RestController
@RequestMapping
public class Controller {
@Value("${myapp.bot-token}") String token
private String token;
@PostMapping(token)// Problem is here
public ResponseEntity<?> getMessage(@RequestBody String payload) {
return new ResponseEntity<HttpStatus>(HttpStatus.OK);
}
}
When I do something like this the problem will gone. But I don’t want to declare my token in source-code.
@RestController
@RequestMapping
public class Controller {
private final String TOKEN = "SOME-TOKEN";
@PostMapping(TOKEN)// No problem
public ResponseEntity<?> getMessage(@RequestBody String payload) {
return new ResponseEntity<HttpStatus>(HttpStatus.OK);
}
}
Can anyone please give me a solution to this?
2
Answers
Try to paste string with property path inside @PostMapping annotation. Like this
You can only use a constant (i.e. a final static variable) as the parameter for an annotation.
Example:
You must use builder pattern(use Lombok for ease) and freeze the value that you are getting from the
properties
and then use that in your program.