jax-ws web-service层到基于hibernate的数据提供者

时间:2010-10-29 10:04:12

标签: java hibernate architecture jax-ws

数据提供程序(java,hibernate)具有用于访问JPA注释类实例的API。 Web服务(jax-ws)将API暴露给网络客户端。我想解决的一个问题是数据提供者的客户端不能轻易地重新配置为直接使用提供者或通过Web服务。原因是对于任何持久化类,在jax-ws客户端代码和数据提供者代码中都有这个类的定义,它们在结构上是相同的,但在Java中是不同的类。将生成的类放入与原始类相同的命名空间并以总生成类的方式设置类路径的明显解决方案似乎不是一个干净的解决方案。

有没有人解决这个问题或知道更好的方法?

1 个答案:

答案 0 :(得分:1)

我在类似问题中解决这个问题的一种方法是使用接口并使用反射来构建包装真实底层对象的代理对象。类似的东西:

interface IEntity
{
    void setFoo(String foo);

    String getFoo();
}

class WSEntity
{/* code generated by jax-ws */
}

class DataEntity
{ /* code generated by java, hibernate, .. */
}

class WSEntityInvocationHandler implements InvocationHandler
{
    private final WSEntity entity;

    public WSEntityInvocationHandler(WSEntity entity)
    {
        this.entity = entity;
    }

    public Object invoke(Object proxy, 
                         Method method, Object[] args) throws Throwable
    {
        // this is a simplified version
        Method m = entity.getClass().getMethod(method.getName(), params);
        return m.invoke(entity, args);
    }
}

static void example()
{
    InvocationHandler handler = new WSEntityInvocationHandler(entity);
    IEntity ie = (IEntity) Proxy
                 .newProxyInstance(IEntity.class.getClassLoader(),
                                                  new Class[]{IEntity.class},
                                                  handler);
}

基本上你的所有app都需要做,决定使用哪个“调用处理程序”,例如

InvocationHandler handler = new WSEntityInvocationHandler(entity);

InvocationHandler handler = new DataEntityInvocationHandler(entity);