How to get the host name in spring configuration file?

Gopi picture Gopi · Dec 5, 2015 · Viewed 7.4k times · Source

Is there any easy way to get the host name in spring configuration file ? Currently I am using Java code to get the host name and and auto wire the property in the bean . But looking for less coding approach if any !

Thanks

Answer

Kabir picture Kabir · Dec 5, 2015

The following will give you the hostname in java

return InetAddress.getLocalHost().getHostName();

where InetAddress belongs to the java.net package. You can add that to your java configuration file. If you want to do it in xml, you can do the following

<bean id="localhostInetAddress"
    class="java.net.InetAddress"
    factory-method="getLocalHost"/>

<bean id="hostname"
    factory-bean="localhostInetAddress"
    factory-method="getHostName"/>