Skip to content
Advertisement

Is it okay to declare Spring MVC response DTOs as static nested classes?

Sometimes it is very convenient to use Spring MVC automatic object-JSON conversion feature when you are designing RESTful API for your web application. For this feature to work, one needs to define a custom class that will be serialized.

Consider this snippet of code:

@RestController
public class ClientLogin {

    @PostMapping("/auth/password")
    public AuthResponse doPasswordLogin(@RequestParam String username, @RequestParam String password) {
        ...
        return new AuthResponse("test username", "test accessToken", "test sessionToken");
    }

    @PostMapping("/auth/token")
    public AuthResponse doTokenLogin(@RequestParam String username, @RequestParam String token) {
        ...
        return new AuthResponse("test username", "test new accessToken", "test sessionToken");
    }

    @RequiredArgsConstructor
    @Getter
    public static class AuthResponse {
        private final String username;
        private final String accessToken;
        private final String sessionToken;
    }
}

My question is if it is a good idea to define these “response” classes in the endpoint classes directly, or if it is better to create separate files for such classes? Keep in mind, the AuthResponse object is not being used by any other endpoint with the exception of unit tests.

Advertisement

Answer

In real-life projects, you’ll need to map models coming from business layer into presentation layer models (in your case it’s AuthResponse). This mapping should be unit-tested, and in order to access AuthResponse in your test, you’ll need to specify the ClientLogin controller in the imports through import <package_name>.ClientLogin.AuthResponse. I would recommend keeping your code as decoupled as possible.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement