[英]Spring boot- inject service into doFiler
I am trying to inject a auth service to a Filter
- 我正在尝试向Filter
注入身份验证服务-
@Autowired
AuthRequestService authService;
And use it in doFiler
method - 并在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);
}
My filter class in sub-package of my @SpringBootApplication
class and annotated with @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;
}
}
The class also appears when listing all my beans using - 当使用-列出我的所有豆子时,该类也会出现
for (String name : applicationContext.getBeanDefinitionNames()) {
System.out.println(name);
}
Still when debugging authService
is null, one last thing the filter is registered with FilterRegistrationBean
- 仍然在调试authService
为null时,最后一件事是使用FilterRegistrationBean
注册了过滤器-
FilterRegistrationBean<SAPServiceFilter> filterRegBean = new FilterRegistrationBean<>();
filterRegBean.setFilter(new SAPServiceFilter());
You could use constructor injection. 您可以使用构造函数注入。 Supposed your filter registration bean lives in a component and has access to the service you could autowire it there and pass it with the constructor 假设您的过滤器注册bean位于一个组件中,并且可以访问该服务,您可以在其中自动装配并传递给构造函数
@Autowired
AuthRequestService authRequestService;
[...]
FilterRegistrationBean<SAPServiceFilter> filterRegBean = new FilterRegistrationBean<>();
filterRegBean.setFilter(new SAPServiceFilter(authRequestService));
Your filter is not under the control of spring. 您的过滤器不受弹簧控制。 That´s why the autowired dependencies are not being injected. 这就是为什么不自动插入依赖项的原因。
In your filter init code add this line: 在过滤器初始化代码中添加以下行:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
or 要么
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,getServletContext());
But there are more other ways to register a servlet filter in spring context: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-embedded-container-servlets-filters-listeners-beans 但是还有更多其他方法可以在spring上下文中注册servlet过滤器: https : //docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-embedded-container-servlets-filters-听众豆
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.