Search code examples
javaspringspring-mvc

What Spring controller method return type to use If I want to return type X or Y depending on condition?


I want to create method in Spring controller that returns String or SseEmitter depending on condition.

What return type I should specify in method signature?

@GetMapping("/test")
public WHAT_TO_WRITE_HERE test() {
    if (MyCondition) {
        SseEmitter emitter = new SseEmitter();
        //Fill SseEmitter with data, not related to question
        return emitter;
    } else {
        return "String";
    }
}

Solution

  • You shouldn't do it because it will confuse the API clients. But say you want to do it for testing purposes. Then, you can simply set an Object as a return type.

    Here is an example

    @RestController
    @RequestMapping("/api")
    public class DemoController {
    
    
        @GetMapping("/demo")
        public Object demo() {
            if (new Random().nextBoolean()) {
                return "Hello, World!";
            } else {
                return new User("John Doe", "[email protected]");
            }
        }
    }
    
    @Data
    @AllArgsConstructor
    class User {
        private String name;
        private String email;
    }
    

    Depending on condition, the endpoint will return

    GET http://localhost:8080/api/demo
    
    HTTP/1.1 200 
    Content-Type: application/json
    Transfer-Encoding: chunked
    Date: Fri, 21 Jun 2024 05:20:41 GMT
    
    {
      "name": "John Doe",
      "email": "[email protected]"
    }
    

    or

    GET http://localhost:8080/api/demo
    
    HTTP/1.1 200 
    Content-Type: text/plain;charset=UTF-8
    Content-Length: 13
    Date: Fri, 21 Jun 2024 05:24:56 GMT
    
    Hello, World!