What happens to generic class in jax-ws webservice

2019-05-02 22:17发布

问题:

I want to know if I put a generics method in jax-ws, like:

public List<MyCustomClass> getSomething()

Does the jax-ws support this? On the client side what will the return of the method looks like?

回答1:

You will get a List in the client side (or an array of MyCustomClass objects if the WS consumer is written in another language). That won't be a problem. Remember to always program to interfaces.

Looks like you still don't have much practice creating WS in Java, so I'll give you some advices:

  • You must not send 2 or more objects that contains a circular reference, or you will end with circular reference problems. This is because the JAX-WS tool will create an interminable XML response for the request. It could be very hard to discover. Let's see a case:

    public class ClassA {
        ClassB instanceOfB;
        //getters and setters...
    }
    
    public class ClassB {
        ClassA instanceOfA;
        //getters and setters...
    }
    
    public class MyJAXWS {
    
        @WebMethod
        public ClassA getClassA() {
             ClassA classA = new ClassA();
             ClassB classB = new ClassB();
             classB.setInstanceOfA(classA);
             classA.setInstanceOfB(classB);
             return classA; //boom! circular reference problems!
        }
    }
    
  • You must always have interfaces in your return classes, not specific Java library classes. This means, your classes should have List, Set and Map (in case of containers), because this interfaces are in higher level than the implementation classes, and you could get problems if a non-Java client tries to consume your web service method.

    public class ClassC {
    
        List<ClassA> lstClassA; //good!
        ArrayList<ClassB> alstClassB; //not very flexible with other languages =\
    }
    
  • The classes that will go through your web services should be POJOs (Plain Old Java Objects), not service or business logic layer classes. Why? Because only the attributes values will be marshalled/unmarshalled when communicating with the clients, no method code will appear in the contract of your Web Service.

    public class ClassD {
        private int intValue;
        //naive business logic method
        //won't be generated in the WSDL for the clients/consumers of the Web Services
        public void printIntValue() {
            //pretty simple implementation
            System.out.println(this.intValue);
        }
    }
    

I've faced these three problems in my last SOA project with Java. I hope other people could enhance this answer or provide info with links.



回答2:

Yes, that should not be a problem but usages of array is recommended. As Luiggi mentioned you would receive a List<MyCustomClass>. To add more to can find complete listing of supported types by JAX-WS here



标签: java jax-ws cxf