Dmi*_*try 6 java spring web-services cxf
我已经开始用Spring学习Apache CXF了.首先,我尝试创建一个简单的客户端/服务器模型.
服务器端是: service.HelloWorld.java
@WebService
public interface HelloWorld {
  String sayHi(String text);
}
Run Code Online (Sandbox Code Playgroud)
service.HelloWorldImpl.java
@WebService(endpointInterface = "service.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
   public String sayHi(String text) {
     return "Hello, " + text;
   }
}
Run Code Online (Sandbox Code Playgroud)
客户端是: client.Client.java public class Client {
    public static void main(String[] args) {
          ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new  String[] {"cxf-client-servlet.xml"});
          HelloWorld client = (HelloWorld) context.getBean("client");
          System.out.println(client.sayHi("Batman"));
    }
}
Run Code Online (Sandbox Code Playgroud)
CXF的客户端 - servlet.xml中
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:jaxws="http://cxf.apache.org/jaxws"
 xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://cxf.apache.org/jaxws
    http://cxf.apache.org/schema/jaxws.xsd">
<bean id="client" class="service.HelloWorld" factory-bean="clientFactory" factory-method="create"/>
<bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
    <property name="serviceClass" value="service.HelloWorld"/>
    <property name="address" value="http://localhost:8080/services/HelloWorld"/>
</bean>
Run Code Online (Sandbox Code Playgroud)
问题是:为了使客户端工作,我必须将service.HelloWorld(包+接口)添加到客户端的项目中.我听说过在使用服务之前我需要生成一个存根.所以这对我来说很困惑.那么,什么是正确的方法,什么是最佳实践(可能最好使用一些契约优先方法或类似方法)?后来,我想添加WS-Security,所以我需要一个强大的背景=)
提前致谢.
您可以在客户端使用这样的简单spring配置-
<jaxws:client id="mywebServiceClient"
    serviceClass="com.saurzcode.TestService"
    address="http://saurzcode.com:8088/mockTestService">
    <jaxws:binding>
        <soap:soapBinding version="1.2" mtomEnabled="true" />
    </jaxws:binding>
</jaxws:client>
<cxf:bus>
    <cxf:outInterceptors>
        <bean class="com.saurzcode.ws.caller.SoapHeaderInterceptor" />
    </cxf:outInterceptors>
</cxf:bus>
Run Code Online (Sandbox Code Playgroud)
如果不需要,请忽略拦截器。
如果您正在进行代码优先的 WS 开发,那么分发接口并将其提供给客户端就可以了。我相信@WebService接口上不需要(?)(仅实现),因此客户端不依赖于此注释。
即使您正在执行代码优先的 Web 服务,您仍然可以下载 Apache CXF 为您生成的 WSDL 文档并将其提供给客户端。使用这种方法(被认为更成熟,更不用说它可以在 .NET 等不同平台上使用),客户端必须生成存根(使用类似 的工具wsdl2java)。此过程本质上将自动创建非常相似的客户端界面。
这就是为什么这么多人喜欢契约优先开发的原因之一 - 使用相同的 WSDL 来生成客户端存根和服务器端 WS 实现。这限制了(意外)不兼容的范围。