user3628479
user3628479

Reputation: 91

Autowired Service not injected when called from Token Filter

I've created a Filter to validate tokens sent by my teamates requests, to do that I get a token key located in my properties through a service I created, but I keep getting a NullPointerException beacause my propertyService isn't getting injected...what am I doing wrong ?

This is my service

@Profile("default")
@PropertySource("classpath:application.properties")
@Configuration
public class PropertyService {

    @Autowired
    private Environment env;

    private static final Logger logger = LogManager.getLogger(PropertyService.class);

    public String getProperty(String property) {
        try {
            String prop = env.getRequiredProperty(property);
            return prop;
        } catch (Exception e) {
            logger.error("some message");
            e.printStackTrace();
            throw new PropertyDoesNotExist();
        }
    }
}

This is my Filter

@Service
public class TokenService extends OncePerRequestFilter {

    private final Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    PropertyService propertyService;

    @Bean
    public FilterRegistrationBean tokenFilter() {
        FilterRegistrationBean filter = new FilterRegistrationBean();
        filter.setFilter(new TokenService());
        filter.addUrlPatterns("/token/*");
        return filter;
    }

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

        String token = request.getHeader("Authorization");
        String tokenKey = propertyService.getProperty("token-key");

        //Do something with the key...

        if (NullValueService.isNull(token)) {
            new CustomExceptionResponse().buildAndWriteCustomExceptionForHandlers(response, CustomExceptionMessage.TOKEN_NOT_FOUND);
        } else if (!validateToken(token)) {
            new CustomExceptionResponse().buildAndWriteCustomExceptionForHandlers(response, CustomExceptionMessage.TOKEN_INVALID);
        } else if (!validateTokenExpiration(token)) {
            new CustomExceptionResponse().buildAndWriteCustomExceptionForHandlers(response, CustomExceptionMessage.TOKEN_EXPIRED);
        }else{
            filterChain.doFilter(request, response);
        }
    }
}

Upvotes: 0

Views: 154

Answers (1)

pvpkiran
pvpkiran

Reputation: 27078

Move your FilterRegistrationBean code to a separate file like this

@Configuration
class Someclass

    @Bean
    public FilterRegistrationBean tokenFilter(TokenService tokenService) { // TokenService will be Autowired by spring. This will have propertyService Autowired in turn.
        FilterRegistrationBean filter = new FilterRegistrationBean();
        filter.setFilter(tokenService);
        filter.addUrlPatterns("/token/*");
        return filter;
    }
}

You should not use new. If you do so, then you lose out on Spring autowiring capabilities, which is exactly what is happening in your case. And hence NPE

Upvotes: 2

Related Questions