Here is the utilities component:
EnvUtil.java
(Put it in the appropriate packaging so that it becomes a component.)
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import java.net.InetAddress; import java.net.UnknownHostException; @Component public class EnvUtil { @Autowired Environment environment; private String port; private String hostname; public String getPort() { if (port == null) port = environment.getProperty("local.server.port"); return port; } public Integer getPortAsInt() { return Integer.valueOf(getPort()); } public String getHostname() throws UnknownHostException {
Example - use the utility:
Then it can enter the utility and call its method.
Here is an example in the controller:
// inject it, @Autowired private EnvUtil envUtil; /** * env * * @return */ @GetMapping(path = "/env") @ResponseBody public Object env() throws UnknownHostException { Map<String, Object> map = new HashMap<>(); map.put("port", envUtil.getPort()); map.put("host", envUtil.getHostname()); return map; }
source share