Search This Blog

Saturday 7 September 2013

Injecting Dependencies in a CXF Endpoint

We have seen how easy it is to create CXF endpoints. In the previous post on WSDL first web services we had defined server endpoints as:
<jaxws:endpoint id="randomWs"
   implementor="com.ws.service.samplews_ns.SampleServiceOperationsPortTypeImpl"
   address="randomService" />
The "randomWs" endpoint is a CXF endpoint capable of processing SOAP requests, It is also a spring managed bean.
As a bean it is possible to inject dependencies into this endpoint. And there comes the problem. How to inject a dependency into a bean defined using the endpoint element ?
The endpoint element does not have any property child element, so the following XML would never work:
<jaxws:endpoint id="randomWs"
   implementor="com.ws.service.samplews_ns.SampleServiceOperationsPortTypeImpl"
   address="randomService">
   <property name="someProp" value="xyz" />
</jaxws:endpoint>
I had the same problem recently and a little google search led to a solution on stack overflow. Accordingly I decided to inject a simple Spring into my endpoint:
public class SampleServiceOperationsPortTypeImpl implements SampleServiceOperationsPortType {

  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  // ...other code
}
The change in XML configuration is as follows:
<bean name="randomWsBean"
   class="com.ws.service.samplews_ns.SampleServiceOperationsPortTypeImpl">
   <property name="name" value="Hi Hello" />
</bean>

<jaxws:endpoint id="randomWs" implementor="#randomWsBean"
   address="randomService" />
As seen here the implementor property does not point to a class but a bean.
Rather than add another attribute (something like implemtor-ref), CXF uses a # at the beginning to indicate that this is a bean. The bean definition on its own can be injected with any number of dependencies.
If we are working with Spring' annotations than this code is not needed. We can keep the implementor attribute with the class name and use the @Autowired annotations. The dependencies will all be injected.

1 comment:

  1. Thanks very much, I'm looking for that 3 days....

    ReplyDelete