java - 从 token 过滤器调用时未注入(inject) Autowiring 服务

标签 java spring-boot

我创建了一个过滤器来验证我的团队请求发送的 token ,为此我通过我创建的服务获取位于我的属性中的 token key ,但我不断收到 NullPointerException 因为我的 propertyService 没有被注入(inject)...我做错了什么?

这是我的服务

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

最佳答案

将 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 Autowiring 功能,这正是你的情况所发生的情况。因此 NPE

关于java - 从 token 过滤器调用时未注入(inject) Autowiring 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60838379/

相关文章:

java - Spring Boot 的 CORS 不在响应 header 中

java - AWS ElasticSearch PreBuiltTransportClient java.lang.NoSuchMethodError

java - 正确的单元测试属性持有者没有平等的实现

java - (关于拦截器)spring @Controller 和 @RestController 的区别

java - 在 spring boot 中导出指标

java - Spring-Data-Redis 与 Jedis putIfAbsent 用于分布式锁 - 不正确的行为

java - java @Value 如何工作?

java - 使用 VScode 的 Spring-Boot 应用程序运行配置

java - 如何告诉 maven-shade-plugin 保留签名?

java - 使用 WebTestClient 在 springBootTest 中禁用安全性