Spring/Spring Core

[Spring] Spring Null 처리 하는 법 (Null-safety)

TheWing 2020. 11. 6. 03:33

Null-safety

  • 목적
    • Annotation 에 마킹하여 IntelliJ나 Tool에 지원을 받아 컴파일 시점에 NullPointerException를 방지하기 위함이다.
  • Spring 5에 추가되었다

Null 관련 애노테이션

  • @NonNull
    • Null허용안함
  • @Nullable
  • @NonNullApi (패키지 레벨 설정)
  • @NonNullFields (패키지 레벨 설정)

예시

EventService 생성

import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

@Service
public class EventService {

    @NonNull
    public String createEvent(@NonNull String name) {
        return "hello " + name;
    }
}

ApplicationRunner 를 구현하여 AppRunner 생성

@Component
public class AppRunner implements ApplicationRunner {
    @Autowired
    EventService eventService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
            eventService.createEvent(null);
    }
}
  • 컴파일 설정을 안 해주었을 때 아래와 같이 표시된다

  • 아무런 효과가 없다.

컴파일 설정

  • Settings → Build, Execution, Deployment → Compiler

  • Configure annotations 클릭

  • Spring 관련 Annotation이 없다
  • +클릭 해준다

  • Spring에 있는걸로 추가

  • 추가 버튼 클릭 후

  • NonNull 추가 후 적용 안될시 IDE 재시작

  • 호버시 이렇게 나온다

Package Level 설정시

  • 추가후

@NonNullApi

package kr.springcoreproject.springapplicationcontext.NullSafety;

import org.springframework.lang.NonNullApi;
  • 패키지 레벨에 NonNull을 설정을 해주고 기본값으로 전부 NonNull을 해주면 Null을 허용하 는곳에만 NonNull을 설정해준다
  • 해당 패키지 이하에 있는 모든 NonNull을 적용한다

References