gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:59:42 25 4
gpt4 key购买 nike

我创建了一个过滤器来验证我的团队请求发送的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com