Oh Chin Boon Oh Chin Boon - 7 months ago 95
reST (reStructuredText) Question

Getting server port and contextPath programmatically - springboot

How can i get the server port and contextPath at runtime?

In application.yml, i am setting these values:

port: 9300
contextPath: '/apis'

In the code, i am building a JSONAPI response to include a reference back to the REST API and therefore the need to programmatically get

"relationships": {
"company": {
"links": {
"related": "/api/v1/users/1/company"
"pets": {
"links": {
"related": "/api/v1/users/1/pets"


String related = port? + contextPath? + "/users" + userId + "company";


Inject Spring Boot properties

If I understood correctly, you wish to retrieve the values at runtime to use them in your code ? You can inject the values this way:

private int port;

private String contextPath;


Alternatively, you could take a look at the Hateoas project, which can generate the link section for you: http://docs.spring.io/spring-hateoas/docs/current/reference/html