Architecture Improvement Through @ControllerAdvice

Logic that queries currently logged-in user information and puts it in the model for each controller method causes code duplication and reduces maintainability. It also becomes a potential cause of NullPointerException that can occur when non-logged-in users access.

To solve this, we introduced @ControllerAdvice. By defining commonly needed user information (userInfo) and like list (likeList) as global model attributes, we concentrated logic that each controller individually managed into one place.


@ControllerAdvice

public class GlobalControllerAdvice {

    @ModelAttribute("likeList")

    public List<Long> addLikeList(@AuthenticationPrincipal UserPrincipal userPrincipal) {

        if (userPrincipal == null) return new ArrayList<>();

        return postLikeService.getLikeList(userPrincipal.getUser().getId());

    }

}

Through this refactoring, controllers became able to focus only on each page’s core business logic, and we secured system stability by centrally managing defensive logic for non-logged-in states.

Link:
Link: » Switch to Korean (한국어로 보기)
Link: » Switch to Japanese (日本語で見る)
Share: