DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body

Trending

  • The Role of Functional Programming in Modern Software Development
  • Enhancing Security With ZTNA in Hybrid and Multi-Cloud Deployments
  • How to Format Articles for DZone
  • How AI Agents Are Transforming Enterprise Automation Architecture
  1. DZone
  2. Coding
  3. Frameworks
  4. Consuming SOAP Service With Apache CXF and Spring

Consuming SOAP Service With Apache CXF and Spring

A guide on how to consume SOAP web services with Apache CXF and Spring Boot. Plus, some extra information on making configurations and logging requests for CFX.

By 
Volkan Gungor user avatar
Volkan Gungor
·
Updated Sep. 21, 21 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
30.9K Views

Join the DZone community and get the full member experience.

Join For Free

Apache CXF and Spring Boot.

SOAP web services are not popular anymore but if you are working with old applications, you probably still have to deal with SOAP web services. I am going to give you an example of how to consume a SOAP service with CXF, how to make a configuration for it, and how to log requests and responses to it.

A Simple Web Service

Before I can consume a web service, I need a simple web service to work with. For the project, I am going to use Spring Boot version 2.5.0 and Java 11. You can use another version if you like; it does not matter as long as the versions are not too old. You can easily create a Spring Boot project with a Spring Initializer. If you use maven, pom.xml should be like this. If you use Java 8, you do not need to have a "JAXB Runtime" dependency.

XML
 
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cfxconsumer</groupId>
    <artifactId>soapcxfconsumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>soapcxfconsumer</name>
    <description>Demo spring project for soap consuming with apache cxf</description>
    <properties>
        <java.version>11</java.version>
        <cxf.version>3.3.3</cxf.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
            <version>${cxf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-features-logging</artifactId>
            <version>${cxf.version}</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


First of all, I will create an interface for my simple web service like below. As you see, it will get a single string parameter and returns a string response.

Java
 
@WebService
public interface HelloWorldWS {
    @WebMethod
    String createMessage(@WebParam(name = "createMessageRequest", mode = WebParam.Mode.IN) String name);
}


And, now, I need an implementation of this interface. It will just add "Hello" in front of the input parameter and return it. 

Java
 
@Component
public class HelloWorldWSImpl implements HelloWorldWS{
    @Override
    public String createMessage(String name){
        return "Hello "+name;
    }
}


This is not the topic of this article, so that's why I am not going into detail with CXF configuration. You just have to configure CXF like below.   

Java
 
import javax.xml.ws.Endpoint;
import org.apache.cxf.Bus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import com.cfxconsumer.soapcxfconsumer.ws.HelloWorldWS;

@Configuration
@ImportResource({ "classpath:META-INF/cxf/cxf.xml" })
public class CxfWebServiceConfig {
    @Autowired
    private Bus cxfBus;

    @Bean
    public ServletRegistrationBean cxfServlet() {
        org.apache.cxf.transport.servlet.CXFServlet cxfServlet = new org.apache.cxf.transport.servlet.CXFServlet();
        ServletRegistrationBean servletDef = new ServletRegistrationBean<>(cxfServlet, "/ws/*");
        servletDef.setLoadOnStartup(1);
        return servletDef;
    }

    @Bean
    public Endpoint helloWorldWebService(HelloWorldWS helloWorldWS) {
        EndpointImpl endpoint = new EndpointImpl(cxfBus, helloWorldWS);
        endpoint.setAddress("/helloWorldWS");
        endpoint.publish();
        return endpoint;
    }
}


Now, if I start my Spring Boot application, I can reach WSDL of my simple web service like this: http://localhost:8080/ws/helloWorldWS?wsdl 

I will just write a test class to test my simple web service as below:

Java
 
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class HelloWorldWSIT {

    private HelloWorldWS testClient;

    @BeforeEach
    public void init(){
        JaxWsProxyFactoryBean jaxWsProxyFactory = new JaxWsProxyFactoryBean();
        jaxWsProxyFactory.setServiceClass(HelloWorldWS.class);
        jaxWsProxyFactory.setServiceName(new QName(
                "http://ws.soapcxfconsumer.cfxconsumer.com/",
                "HelloWorldWSImplService"
        ));
        jaxWsProxyFactory.setAddress("http://localhost:8080/ws/helloWorldWS");
        testClient = jaxWsProxyFactory.create(HelloWorldWS.class);
    }

    @Test
    void name() {
        System.out.println("soap response: "+ testClient.createMessage("General Kenobi"));
    }
}


As I run it, I see the below output. My web service works, now let's get to the point.

Test output


Web Service Client Consumer Configuration

If you like, you can start a new project like the previous one to consume the HelloWorld web service. Before consuming a web service, I need a client jar file. I am going to use wsimport utility to create a client jar file, with a command like this; 

wsimport -clientjar helloWorldWSClient.jar "http://localhost:8080/ws/helloWorldWS?wsdl" 

Client jar is created and I need to add it to the project as a dependency. After that, I can create a CXF configuration for it like below:

Java
 
import java.util.HashMap;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import org.apache.cxf.ext.logging.LoggingFeature;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HelloWorldWSClientConfig {

    @Bean
    public LoggingFeature loggingFeature() {
        LoggingFeature loggingFeature = new LoggingFeature();
        loggingFeature.setPrettyLogging(true);
        return loggingFeature;
    }

    @Bean(name = "helloWorldWSClient")
    public HelloWorldWS helloWorldWSService(@Autowired LoggingFeature loggingFeature){
        JaxWsProxyFactoryBean fb = new JaxWsProxyFactoryBean();
        fb.setServiceClass(HelloWorldWS.class);
        fb.setWsdlLocation("/META-INF/wsdl/HelloWorldWSService.wsdl");
        fb.setServiceName(new QName("http://ws.soapcxfconsumer.cfxconsumer.com/",
                "HelloWorldWSImplService"));

        Map<String, Object> properties = fb.getProperties();
        if(properties == null){
            properties = new HashMap<>();
        }

        properties.put("javax.xml.ws.client.connectionTimeout", 5000);
        properties.put("javax.xml.ws.client.receiveTimeout", 3000);

        fb.setProperties(properties);

        fb.getFeatures().add(loggingFeature);

        HelloWorldWS theService = (HelloWorldWS) fb.create();
        BindingProvider bindingProvider = (BindingProvider) theService;
        bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:8080/ws/helloWorldWS");

        return theService;
    }
}


I created a bean name as helloWorldWSClient, as you see. HelloWorldWS.class is the service class included in the client jar file. WSDL location is the path of the WSDL file in the jar file. serviceName consists of namespace and port name. You can put some configuration parameters into the properties map (like connection and socket timeout values). And the last thing to do is to set the endpoint of the service.

The LoggingFeature is required to log outgoing requests and incoming responses. If you want to log them you just have to put the below line into the application.properties file:

logging.level.org.apache.cxf.services = INFO 

This will cause all CXF clients to log requests and responses. If you want to log only a specific service, then you need to have log configs like below. 

Java
 
logging.level.org.apache.cxf.services.HelloWorldWS.REQ_OUT = INFO
logging.level.org.apache.cxf.services.HelloWorldWS.RESP_IN = INFO


As it is obvious, you can use the service class name to log a specific service.

Consumer Web Service

Once the configuration is done, I am ready to call and consume our soap service. First of all, I am going to create a consumer service like below:

Java
 
@Service
public class HelloWorldWSConsumerService {
    private final HelloWorldWS helloWorldWSClient;

    public HelloWorldWSConsumerService(HelloWorldWS helloWorldWS){
        this.helloWorldWSClient = helloWorldWS;
    }

    public String callHelloWorld(String name){
        return helloWorldWSClient.createMessage(name);
    }
}


Now, I need to test this consumer service. I am going to write a simple test class with a simple assertion. 

Java
 
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloWorldWSConsumerServiceIT {
    @Autowired
    private HelloWorldWSConsumerService helloWorldWSConsumerService;

    @Test
    void testCallHelloWorld() {
        Assertions.assertEquals("Hello General Kenobi",
                helloWorldWSConsumerService.callHelloWorld("General Kenobi"));
    }
}


After running this test, let's look at the console output. 

Code screenshot.

That's all.

Spring Framework Web Service SOAP Web Protocols Apache CXF

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!