A "NullPointerException" could be thrown; "getListenerContainer()" can return null.

2022, Sep 08    

problem

  • java:S2259

S2259.png

private final KafkaListenerEndpointRegistry registry;

public void register() {
        try {
            registry.getListenerContainer(LicenseEventSubscriber.ID).start();
        } catch (Exception e) {
            log.error("registry load failed.", e);
        }
    }
  • 서비스가 올라가면 kafka listener에 해당 이벤트 수신을 등록하려는 코드인데, spring boot 버전을 2.7로 올리고 나서 갑자기 sonarqube에서 버그로 잡혔다.

cause

sonarqube 설명을 보면

[Null pointers should not be dereferenced]

A reference to null should never be dereferenced/accessed. 
Doing so will cause a NullPointerException to be thrown. 
At best, such an exception will cause abrupt program termination. 
At worst, it could expose debugging information that would be useful to an attacker, 
or it could allow an attacker to bypass security measures.

Note that when they are present, 
this rule takes advantage of @CheckForNull and @Nonnull annotations 
defined in JSR-305 to understand 
which values are and are not nullable except 
when @Nonnull is used on the parameter to equals, 
which by contract should always work with null.
  • registry가 null이 될 수 있는데, null을 참조하거나 액서스하면 안된다는 뜻인 것 같다.

solve

  1. 실제로 null이 될 가능성이 없다면, surpress를 주거나, fixed 처리를 하면 되고
  2. 만약에 method파라미터라면 @NotNull annotation을 줘서 처리할 수 있다.

reference

A “NullPointerException” could be thrown; “context” is nullable here