Oh Chin Boon Oh Chin Boon - 1 month ago 25
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:

server:
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"
}
}
}
}


Example,

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

Answer

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:

@Value("${server.port}")
private int port;

@Value("${server.contextPath}")
private String contextPath;

Hateoas

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