Skip to main content

SOAP service development using Spring boot and Apache CXF

In this tutorial we are going to learn how to develop a SOAP web service using Spring boot and Apache CXF. We will follow the contract first approach to develop our service where we will use jaxb2 maven plugin to generate the java classes which we will use for service implementation.

Why contract first

With contract first our primary focus stays with the contract of service to be implemented. Also it is useful to match the input/output with business requirement. We can share the contract with other business units/ customers or users, so it helps them to start early without waiting for the complete implementation. Once our contract is ready we can generate the Java classes using jaxb plugin which generates the java objects using the schema for SOAP contract and we need to focus only on service implementation.

SOAP service development (Hello service)

This service will have one operation where user can send their name and in response they will get a hello message with the passed name.
Here we will create a maven project. There are multiple ways to create a maven project like using IDE features, maven command or using spring initializer (http://start.spring.io/).
Below are the steps given in sequence which we will follow to develop our service.

Maven dependencies

I have used Spring boot version as 2.2.2.RELEASE using below parent tag declaration.
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/>
    </parent>
Add below dependencies for spring web and Apache CXF.
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
        <version>3.3.4</version>
    </dependency>

Service contract using XML schema

Service contract is defined below using XML schema where we have defined request and response schema. Request contains one parameter for user name to pass in request and response has one parameter to send the response message.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:tns="http://services.ttj.com/hello-service"
           targetNamespace="http://services.ttj.com/hello-service" elementFormDefault="qualified">

    <xs:element name="sayHelloRequest">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="userName" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="sayHelloResponse">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="message" type="xs:string"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

Java classes generation from XSD contract

Add below plugin to pom.xml. Specify the schema location in schemDirectory tag and package location for new classes as given below. Please refer the link https://www.thetechnojournals.com/2019/10/jaxb2-maven-plugin-to-generate-java.html for more details on class generation from XML schema.
    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jaxb2-maven-plugin</artifactId>
        <version>1.6</version>
        <executions>
            <execution>
        <id>xjc</id>
        <goals>
            <goal>xjc</goal>
        </goals>
            </execution>
        </executions>
        <configuration>
            <schemaDirectory>${project.basedir}/src/main/resources/schema</schemaDirectory>
            <outputDirectory>${project.basedir}/src/main/java</outputDirectory>
            <clearOutputDir>false</clearOutputDir>
        </configuration>
    </plugin>
Now build the project using maven build. It will generate the new package and classes using the XML contract. Once these classes are generated, we can proceed with further steps

CXF servlet and bus configuration

We need to create a servlet dispatcher bean to map the services URL with CXF servlet. Also we will create a SpringBus bean, however you don't need to create the SpringBus bean but if you want to add some additional features like interceptors, security etc. then you should declare this bean and bind additional features to it.
@Configuration
public class CxfConfig {
    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus(){
        SpringBus bus = new SpringBus();
        return bus;
    }

    @Bean
    public ServletRegistrationBean<CXFServlet> messageDispatcherServlet(
            ApplicationContext applicationContext, SpringBus springBus){

        CXFServlet cxfServlet = new CXFServlet();
        cxfServlet.setBus(springBus);
        return new ServletRegistrationBean<>(cxfServlet, "/*");
    }
}

Service implementation

Now we will create the service class which will read the soap request and generate the response accordingly. It can be implemented by creating interface also but here I am creating only implementation class. If you create through interfaces please put all annotations to interface and then implement in your service class.
@WebService(serviceName = "hello-service")
public class HelloServiceEndpoint {
    @WebMethod(action="sayHello", operationName = "sayHelloRequest")
    @WebResult(name = "message")
    public String sayHello(SayHelloRequest request){
        return "Hello "+request.getUserName()+"!!!";
    }
}

Service endpoint configuration

Finally we need to create the endpoint for our web service which will be published using the specified endpoint.
@Configuration
public class SoapEndpointsConfig {

    @Bean
    public Endpoint endpoint(SpringBus bus) {
        EndpointImpl endpoint = new EndpointImpl(bus, new HelloServiceEndpoint());
        endpoint.publish("/helloService");
        return endpoint;
    }
}

Running and testing web service using SOAP UI

Now build the maven project and run it using below command.
Once your application is started, please enter below URL in browser.
http://localhost:8080/helloService?wsdl
If you are able to see the WSDL content then it means your service is up and ready for testing. You will see similar screen as given below.
wsdl
Now open the SoapUI and create a new Soap Project by giving the above WSDL URL. It will create a project with sample request also.
Open the request XML and verify that it has correct name space for service schema, if not then you can add it there. In my case it didn't add all namespace, so I added it manually. Now execute the request and you will see the response with hello message as given below.
soap request execution

Source code

You can download the complete source code form below github location.
https://github.com/thetechnojournals/spring-tutorials/tree/master/CxfSoapService

Other posts you may be interested in:

https://www.thetechnojournals.com/2019/10/soap-request-ssl-signature-validation.html

https://www.thetechnojournals.com/2020/02/xml-validation-using-xsd-schema.html

Comments

  1. IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Projects for CSE It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai


    The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

    ReplyDelete

Post a Comment

Popular Posts

Setting up kerberos in Mac OS X

Kerberos in MAC OS X Kerberos authentication allows the computers in same domain network to authenticate certain services with prompting the user for credentials. MAC OS X comes with Heimdal Kerberos which is an alternate implementation of the kerberos and uses LDAP as identity management database. Here we are going to learn how to setup a kerberos on MAC OS X which we will configure latter in our application. Installing Kerberos In MAC we can use Homebrew for installing any software package. Homebrew makes it very easy to install the kerberos by just executing a simple command as given below. brew install krb5 Once installation is complete, we need to set the below export commands in user's profile which will make the kerberos utility commands and compiler available to execute from anywhere. Open user's bash profile: vi ~/.bash_profile Add below lines: export PATH=/usr/local/opt/krb5/bin:$PATH export PATH=/usr/local/opt/krb5/sbin:$PATH export LDFLAGS=&

SpringBoot - @ConditionalOnProperty example for conditional bean initialization

@ConditionalOnProperty annotation is used to check if specified property available in the environment or it matches some specific value so it can control the execution of some part of code like bean creation. It may be useful in many cases for example enable/disable service if specific property is available. Below are the attributes which can be used for property check. havingValue - Provide the value which need to check against specified property otherwise it will check that value should not be false. matchIfMissing - If true it will match the condition and execute the annotated code when property itself is not available in environment. name - Name of the property to be tested. If you want to test single property then you can directly put the property name as string like "property.name" and if you have multiple properties to test then you can put the names like {"prop.name1","prop.name2"} prefix - It can be use when you want to apply some prefix to

Spring Batch tutorial with example

Spring batch is used to create and process the batch jobs. It provides various features like logging, job statistics, transaction management, restarting jobs. It is very helpful in processing of large dataset but with finite volume of data. In this tutorial we will learn how to create and execute the spring batch job. In our example we will create a job which will import all the words from a text file to database and then at last it will print the total number of words available in the database. Below is the project structure. Creating batch job Sample text file to import Below is the contents of text file which we use for importing the words. The list below gives you the 1000 most frequently used English words in alphabetical order. Once you've mastered the shorter vocabulary lists, this is the next step. It would take time to learn the entire list from scratch, but you are probably already familiar with some of these words. Feel free to copy this list into

Multiple data source with Spring boot, batch and cloud task

Here we will see how we can configure different datasource for application and batch. By default, Spring batch stores the job details and execution details in database. If separate data source is not configured for spring batch then it will use the available data source in your application if configured and create batch related tables there. Which may be the unwanted burden on application database and we would like to configure separate database for spring batch. To overcome this situation we will configure the different datasource for spring batch using in-memory database, since we don't want to store batch job details permanently. Other thing is the configuration of  spring cloud task in case of multiple datasource and it must point to the same data source which is pointed by spring batch. In below sections, we will se how to configure application, batch and cloud task related data sources. Application Data Source Define the data source in application properties or yml con