简体   繁体   中英

Create bean and call non-setter method

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));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM