springboot Unboxing of redisTemplate. may produce NullPointerException

1.8k views Asked by At

I use springboot(2.3.1) and Lettuce in project

Filter

@Slf4j
@WebFilter(filterName = "requestWrapperFilter", urlPatterns = {"/*"})
public class RequestWrapperFilter implements Filter {
    @Resource
    private RedisTemplate redisTemplate;
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    ...
                if (redisTemplate.hasKey(COMMON_HEAD_TOKEN_NAME + token)) {
                    redisTemplate.delete(COMMON_HEAD_TOKEN_NAME + token);
                }
    }
    ...
}

the RedisConfig configration like this:

@Configuration
@Component
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }
}

but when I calling interface , the application shows the following error:

there is WARNING:

Unboxing of 'redisTemplate.hasKey(COMMON_HEAD_TOKEN_NAME + token)' may produce 'NullPointerException' 
Unchecked call to 'hasKey(K)' as a member of raw type 'org.springframework.data.redis.core.RedisTemplate' 

can I ignore ?

1

There are 1 answers

0
Forketyfork On BEST ANSWER

The first warning means that the hasKey method returns an object wrapper, but using it inside an if condition implicitly unboxes it (i.e. converts the result of the call to a primitive value). If for some reason the hasKey method returns null, you'll get an error. To be on the safe side, check the presence of the key as follows:

if (Boolean.TRUE.equals(redisTemplate.hasKey(COMMON_HEAD_TOKEN_NAME + token))) {

The second warning means that your redisTemplate field has a raw type, however, the RedisTemplate class is parameterized. To get rid of the warning, define the redisTemplate field in the filter as follows:

@Resource
private RedisTemplate<String, Serializable> redisTemplate;