1.建立xml报文转换接口;
public interface XmlBeanConverter {
//xml转对象
T fromXml(String xml, Class targetClass, String encoding);
//对象转xml
StringtoXml(Object xmlObject, String encoding);
}
2.建立公共的抽象类,2个方法,1个方法调用远程调用返回结果,一个方法报文解析返回对象:
public abstract class NbSmWebServiceInvoctionBuildimplements XmlBeanConverter {
@Autowired
private NbWebServiceInvocationServiceNbWebServiceInvocationService;
//远程调用返回xml报文
public StringdoInvoke(String requestXml, String sjblx) {
long timeStart = System.currentTimeMillis();
String responseXml =NbWebServiceInvocationService.innerInvoke(sjblx, requestXml);
long timecost = System.currentTimeMillis() - timeStart;
return responseXml;
}
//解析xml报文转对象
@Override
public T fromXml(String xml, Class targetClass, String encoding) {
JaxbXmlBeanConverter jaxbXmlBeanConverter =new JaxbXmlBeanConverter();
return jaxbXmlBeanConverter.fromXml(xml, targetClass, "utf-8");
}
}
3.建立工厂类,工厂类只有一个方法,生产返回对象
public class Factory {
public Objectfactory(NbSmWebServiceInvoctionBuild builder,Object request,String sjblx,Class responseClass){
String toXml = builder.toXml(request, "utf-8");
String fromXml = builder.doInvoke(toXml, sjblx);
return builder.fromXml(fromXml,responseClass,"utf-8");
}
}
4.每次使用只需要新建一个类继承NbSmWebServiceInvoctionBuild抽象类,实现toXml方法,:
public class NbSmWebServiceInvoctionJtBuild extends NbSmWebServiceInvoctionBuild {
@Override
public StringtoXml(Object xmlObject, String encoding) {
return "xml";
}
}
5.使用:
public class Test {
public static void main(String[] args) {
Factory factory=new Factory();
NbSmWebServiceInvoctionBuild jtBuild=new NbSmWebServiceInvoctionJtBuild();
Object request=new Object();
Object respsonse = factory.factory(jtBuild, request, "sjlx", null);
System.out.println(respsonse.toString());
}
}
总结:封装了内部的调用细节,每次根据不同的请求参数,返回相应的处理结果;
网友评论