Служба Autowired не вводится при вызове из Token Filter - PullRequest
0 голосов
/ 24 марта 2020

Я создал Фильтр для проверки токенов, отправленных моими запросами teamates, для этого я получаю ключ токена, расположенный в моих свойствах через созданный мной сервис, но я продолжаю получать исключение NullPointerException, потому что мой propertyService не вводится ... что я делаю не так?

Это мой сервис

@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();
        }
    }
}

Это мой фильтр

@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);
        }
    }
}

1 Ответ

2 голосов
/ 24 марта 2020

Переместите код FilterRegistrationBean в отдельный файл, подобный этому

@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;
    }
}

Вам не следует использовать new. Если вы сделаете это, то потеряете возможности автоматического подключения Spring, что и происходит в вашем случае. И, следовательно, NPE

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...