我正在尝试将身份验证服务注入Filter-
Filter
@Autowired AuthRequestService authService;
并在doFiler方法中使用它-
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-
@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-
authService
FilterRegistrationBean
FilterRegistrationBean<SAPServiceFilter> filterRegBean = new FilterRegistrationBean<>(); filterRegBean.setFilter(new SAPServiceFilter());
您可以使用构造函数注入。假设您的过滤器注册Bean位于组件中,并且可以访问该服务,您可以在其中自动进行连接并将其传递给构造函数
@Autowired AuthRequestService authRequestService; [...] FilterRegistrationBean<SAPServiceFilter> filterRegBean = new FilterRegistrationBean<>(); filterRegBean.setFilter(new SAPServiceFilter(authRequestService));