I need to fill a property of a bean with the current hostname just like the call returns it: InetAddress.getLocalHost().getHostName()
It should be something like so:
<bean id="hostname" value="InetAddress.getLocalHost().getHostName()" />
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="schedulerName" ref="hostname" />
</bean>
This can be done somewhat simply with xml, as detailed in sections 3.3.2.2 and 3.3.2.3 of the Spring documentation.
In summary, section 3.3.2.2 suggests a method of invoking a static method of a class. This can be done as so:
<bean id="myBean"
class="com.foo.MyClass"
factory-method="myStaticMethod"/>
This will create a bean in the ApplicationContext with a name of myBean, which is populated by the returned object from an invokation of MyClass.myStaticMethod().
But this is only halfway there, as we only have the result of the static method (the first call in your case).
Section 3.3.2.3 details how to invoke a non-static method of a bean that lives in the ApplicationContext already. It can be done as so:
<bean id="myOtherBean"
factory-bean="myBean"
factory-method="myNonStaticMethod"/>
This will create a bean in the ApplicationContext with a name of myOtherBean, which is populated by the returned object from an invokation of myBean.myNonStaticMethod(), where myBean is the bean pulled from the ApplicationContext.
When put together, you should be able to achieve what you are after.
<bean id="localhostInetAddress"
class="java.net.InetAddress"
factory-method="getLocalHost"/>
<bean id="hostname"
factory-bean="localhostInetAddress"
factory-method="getHostName"/>
Of course the easier way to do this is with Java Configuration.
@Configuration
public class InetConfig {
@Bean
public String hostname() {
return InetAddress.getLocalHost().getHostName();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With