我正在尝试向Filter
-
@Autowired
AuthRequestService authService;
并以doFiler
方法使用它-
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
System.out.println("SAPServiceFilter: "+ req.getRequestURI());
//TODO - create auth sender
authService.isAuthnticate((HttpServletRequest)request); //null
chain.doFilter(request, response);
}
我的@SpringBootApplication
类的子包中的过滤器类,并带有@service
-
@Service
public class AuthRequestService {
@PostConstruct
public void init() {
System.out.println("AuthRequestService @PostConstruct");
}
public boolean isAuthnticate(HttpServletRequest request) {
System.out.println("isAuthnticate");
return true;
}
}
使用-列出我所有的豆子时,该类也会出现
for (String name : applicationContext.getBeanDefinitionNames()) {
System.out.println(name);
}
在调试authService
为null时,仍然在FilterRegistrationBean
中注册了过滤器的最后一件事-
FilterRegistrationBean<SAPServiceFilter> filterRegBean = new FilterRegistrationBean<>();
filterRegBean.setFilter(new SAPServiceFilter());
答案 0 :(得分:1)
您可以使用构造函数注入。假设您的过滤器注册bean位于一个组件中,并且可以访问该服务,您可以在其中自动装配并传递给构造函数
@Autowired
AuthRequestService authRequestService;
[...]
FilterRegistrationBean<SAPServiceFilter> filterRegBean = new FilterRegistrationBean<>();
filterRegBean.setFilter(new SAPServiceFilter(authRequestService));
答案 1 :(得分:0)
您的过滤器不受弹簧控制。这就是为什么不自动插入依赖项的原因。
在过滤器初始化代码中添加以下行:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
或
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,getServletContext());
但是还有更多其他方法可以在spring上下文中注册servlet过滤器: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-embedded-container-servlets-filters-listeners-beans