Home > Back-end >  Java Generic Response Issue in Spring Boot
Java Generic Response Issue in Spring Boot

Time:10-12

I have a problem about making a jeneric response for this method in my Spring Boot example. In signup, there are two response type (Generic message and UserDto). That's why I want to use jeneric response but I couldn't do that.

How can I do that?

Here is the method shown below.

public (Generic Resposne) signup(SignUpRequest signUpRequest){
    ....
    return MessageResponse.builder()
                    .message("Error: Username is already taken!")
                    .build();
    ....
    return UserDto.builder()
                .id(user.getId())
                .username(user.getUsername())
                .build();
}

CodePudding user response:

You can create an interface and implement both other types with it.

public interface Response
public class UserDto implements Response
public class MessageResponse implements Response
public Response signup(SignUpRequest signUpRequest){
    ....
    return MessageResponse.builder()
                    .message("Error: Username is already taken!")
                    .build();
    ....
    return UserDto.builder()
                .id(user.getId())
                .username(user.getUsername())
                .build();
}
  • Related