개발강의정리/Spring

[스프링 프레임워크 핵심 기술] 7-1. Null-safety

nineDeveloper 2019. 10. 7.
728x90

스프링 프레임워크 핵심 기술

포스팅 참조 정보

GitHub

공부한 내용은 GitHub에 공부용 Organizations에 정리 하고 있습니다

해당 포스팅에 대한 내용의 GitHub 주소

실습 내용이나 자세한 소스코드는 GitHub에 있습니다
포스팅 내용은 간략하게 추린 핵심 내용만 포스팅되어 있습니다

https://github.com/freespringlecture/spring-core-tech/tree/chap07-01-nullsafety

 

freespringlecture/spring-core-tech

백기선님의 스프링 프레임워크 핵심 기술 강의 내용 정리. Contribute to freespringlecture/spring-core-tech development by creating an account on GitHub.

github.com

해당 포스팅 참고 인프런 강의

https://www.inflearn.com/course/spring-framework_core/dashboard

 

스프링 프레임워크 핵심 기술 - 인프런

이번 강좌는 스프링 부트를 사용하며 스프링 핵심 기술을 학습합니다 따라서 스프링 부트 기반의 프로젝트를 사용하고 있는 개발자 또는 학생에게 유용한 스프링 강좌입니다. 초급 웹 개발 Java Spring 온라인 강의

www.inflearn.com

실습 환경

  • Java Version: Java 11
  • SpringBoot Version: 2.1.2.RELEASE

7-1. Null-safety

스프링 프레임워크 5에 추가된 Null 관련 애노테이션
Spring Data 와 Reactor에서 사용함

  • @NonNull
  • @Nullable
  • @NonNullApi (패키지 레벨 설정)
  • @NonNullFields (패키지 레벨 설정)

목적

Null을 허용하느냐 Null을 허용하지 않느냐를 애노테이션으로 마킹 해놓고
(툴의 지원을 받아) 컴파일 시점에 최대한 NullPointerException을 미연에 방지하는 것

@NonNull 예제

  • 받는 쪽 구현

    @Service
    public class EventService {
    
      @NonNull
      public String createEvent(@NonNull String name) {
          return null;
      }
    }
  • 보내는 쪽 구현

    @Component
    public class AppRunner implements ApplicationRunner {
    
      @Autowired
      EventService eventService;
    
      @Override
      public void run(ApplicationArguments args) throws Exception {
          eventService.createEvent("freelife");
      }
    }

@NonNullApi 예제

package-info.java 파일을 추가하고 패키지에 @NonNullApi를 적용하면
해당 패키지의 모든 파라메터와 리턴타입 @NonNull을 적용하는 것과 마찬가지 임
패키지에 전부 @NonNull을 적용하고 Null을 허용하는 곳에만 @Nullable을 붙이는 방식의 코딩이 가능함

@NonNullApi
package me.freelife;

import org.springframework.lang.NonNullApi;

intellij 설정 위치

위치: Build, Excution, Deployment -> Compiler -> Configure annotations...

  1. Nullable annotationsorg.springframework.lang.Nullable 추가
  2. NotNull annotationsorg.springframework.lang.NonNull 추가
  3. intellij 재시작
  4. Passing 'null' argument to parameter annotated as @NotNull 보내는 쪽이 null이면 이런 메세지가 보임
  5. 'null' is returned by the method declared as @NonNull 받는 쪽이 null일 경우 이런 메세지가 보임
728x90

댓글

💲 추천 글