Issue
How can I create the following code into a Client bean in spring.xml so that I can inject Client(Object) into my Code ? I am configuring this bean to get data from elastic search.
Client client = new TransportClient().addTransportAddress(new InetSocketTransportAddress("192.168.0.198",9300));
Solution
Create a Spring FactoryBean that allows you to expose a Client bean and is easy to configure as a bean in Spring application context. For example
public class ClientFactoryBean implements FactoryBean<Client>{
private String ipAddress;
private int port;
public Class<?> getObjectType(){
return Client.class;
}
public boolean isSingleton(){
return true;
}
public void setPort(int port){
this.port = port;
}
public void setIpAddress(String ipAddress){
this.ipAddress = ipAddress;
}
public Client getObject(){
return new TransportClient().addTransportAddress(new InetSocketTransportAddress(ipAddress,port));
}
}
Then in your application context file
<bean id="client" class="some.package.ClientFactoryBean">
<property name="ipAddress" value="192.168.0.198"/>
<propert name="port" value="9300"/>
</bean>
You can then inject the client bean as usually. NB. Its type will be Client not ClientFactoryBean as Spring will detect that its a factory bean and it will manage the result of the getObject call
Answered By - ekem chitsiga
Answer Checked By - Willingham (JavaFixing Volunteer)