Apache CXF with JMS JAX-WS Example
www.igioc.aeditfm
here's an example of how to use Apache CXF to create a JMS service using JAX-WS.
- First, we need to add the CXF dependencies to our project. We can do this by adding the following dependencies to our Maven pom.xml file:
<dependencies> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-jms</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-bindings-xml</artifactId> <version>3.4.5</version> </dependency> </dependencies>
- Next, we can create a service interface that will define our JMS service. Let's create an interface called "HelloService" that will have a single method called "sayHello" that takes a String parameter and returns a String:
package com.example; import javax.jws.WebMethod; import javax.jws.WebService; @WebService public interface HelloService { @WebMethod String sayHello(String name); }
- We can then create an implementation of this interface. Let's create a class called "HelloServiceImpl" that implements the "HelloService" interface:
package com.example; @WebService(endpointInterface = "com.example.HelloService") public class HelloServiceImpl implements HelloService { public String sayHello(String name) { return "Hello " + name; } }
- Finally, we need to configure the JMS transport for our service. We can do this by creating a file called "cxf.xml" in the "src/main/resources/META-INF" directory. Here's what the file should look like:
<bus> <jaxws:server serviceClass="com.example.HelloService" address="jms://queue:HelloQueue"> <jaxws:serviceFactory> <ref bean="cxf"/> </jaxws:serviceFactory> <jaxws:features> <bean class="org.apache.cxf.feature.LoggingFeature"/> </jaxws:features> <jaxws:endpoint> <cxf:properties> <entry key="dataFormat" value="PAYLOAD"/> <entry key="transport.jms.ConnectionFactory" value="ConnectionFactory"/> </cxf:properties> </jaxws:endpoint> </jaxws:server> </bus>
In this file, we're configuring a JAX-WS server that will listen for messages on the "HelloQueue" JMS queue. We're also setting the data format to "PAYLOAD" and specifying the JMS connection factory to use.
- We can now create a main method that will start up our JMS service. Here's what the main method should look like:
import org.apache.cxf.Bus; import org.apache.cxf.BusFactory; import org.apache.cxf.jaxws.JaxWsServerFactoryBean; public class HelloServicePublisher { public static void main(String[] args) { // Create the CXF bus Bus bus = BusFactory.getDefaultBus(); // Create the JAX-WS server JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean(); factory.setBus(bus); factory.setServiceBean(new