5

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

Gopi
  • 619
  • 2
  • 9
  • 27

1 Answers1

5

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"/>
Kabir
  • 860
  • 5
  • 11
  • Is there a way to refer to the hostname string as a property value from another bean in this file? I had no luck with even though I confirmed that the hostname bean should be a String. This gave me the error: Could not resolve placeholder 'HOSTNAME' in string value "sometext-{$hostname}" – k-den May 18 '16 at 05:19
  • 3
    What worked for me was the localhostInetAddress bean definition along with something like I deleted the id="hostname" bean definition. – k-den May 18 '16 at 06:21