How to resolve null pointer exceptions of autowiring beans inside spring boot OncePerRequestFilter filters?

Viewed 33

I have written OncePerRequestFilter inside my spring boot application where I want to call Redis cache and get a payload. For that I have a comigration class which responsible to maintain Redis connection.

@Configuration
@EnableRedisRepositories
public class RedisConfigurations {

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private Integer redisPort;

    @Value("${spring.redis.password}")
    private String redisPassword;

    @Bean
    public JedisConnectionFactory connectionFactory() {
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName(redisHost);
        configuration.setPort(redisPort);
        return new JedisConnectionFactory(configuration);
    }

    @Bean
    public RedisTemplate<String, Object> template() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory());
        template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
}

So inside my filter.

@Component
public class RequestValidationFilter extends OncePerRequestFilter {
    public static final String HASH_KEY = "USER";

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        String token  = request.getHeader("AUTHORIZATION");
        if(!token.isEmpty()){
            try {
                Claims claims = Jwts.parser()
                        .setSigningKey("superdupersecretkey")
                        .parseClaimsJws(token).getBody();
                String username = String.valueOf(claims.get("username"));
                String authorities = (String) claims.get("authorities");
                
                redisTemplate.opsForHash().values(HASH_KEY);
              Authentication auth = new UsernamePasswordAuthenticationToken(username,null,
                            AuthorityUtils.commaSeparatedStringToAuthorityList(authorities));
                    SecurityContextHolder.getContext().setAuthentication(auth);
            }catch (Exception e) {
                throw new BadCredentialsException("Invalid Token received!");
            }
        }
        filterChain.doFilter(request, response);
    }
}

So @Autowired private RedisTemplate redisTemplate; this code snippet return null pointer.

Why is that?

0 Answers
Related