skip to Main Content

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


  1. Try to paste string with property path inside @PostMapping annotation. Like this

    @GetMapping(value = "${app.path}")
    public String hello() {
        return "hello";
    }
    
    Login or Signup to reply.
    1. You can only use a constant (i.e. a final static variable) as the parameter for an annotation.

      Example:

      @Component
      class Constants {
          public final static String FACEBOOK = "facebook";
      }
      
      @RestController
      class Controller {
          @PostMapping(Constants.FACEBOOK) 
          public ResponseEntity<ResponseBody> getMessage(@RequestBody String payload) {
              return new ResponseEntity<>(HttpStatus.OK);
          }
      }
      
    2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search