Search code examples
javaspringweb-servicestimeoutspring-ws

Setting timeout in Spring's WebServiceTemplate


Is there any way to set programmatically the timeout of Spring's WebServiceTemplate? I've seen old articles about setting it via Message Senders in Application Context config file. But in our project, these objects have been created by code, not by injection.

I need to lower the default timeout as sometimes the customer's endpoint takes too long, and queues up other requests, so I need to force it to fail faster.

PS: Using spring-ws-core-2.2.2.RELEASE.jar


Solution

  • Since Spring Webservices 2.2, you can use Spring's ClientHttpRequestMessageSender:

    @Service
    public class CustomWebServiceImpl extends WebServiceGatewaySupport implements CustomWebService {
        private static final int CONNECTION_TIMEOUT = (10 * 1000);
        private static final int READ_TIMEOUT = (10 * 1000);
    
        public CustomWebServiceImpl() {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            requestFactory.setConnectTimeout(CONNECTION_TIMEOUT);
            requestFactory.setReadTimeout(READ_TIMEOUT);
            setMessageSender(new ClientHttpRequestMessageSender(requestFactory));
        }
    
        (...)
    }