Spring boot-将服务注入doFiler [英] Spring boot- inject service into doFiler
问题描述
我正在尝试向过滤器注入auth服务
-
I am trying to inject a auth service to a Filter
-
@Autowired
AuthRequestService authService;
并在 doFiler
方法中使用它 -
And use it in doFiler
method -
@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
进行注释 -
My filter class in sub-package of my @SpringBootApplication
class and annotated with @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;
}
}
使用以下内容列出我所有的bean时,也会显示该类
The class also appears when listing all my beans using -
for (String name : applicationContext.getBeanDefinitionNames()) {
System.out.println(name);
}
仍在调试 authService
为null,过滤器注册的最后一件事是 FilterRegistrationBean
-
Still when debugging authService
is null, one last thing the filter is registered with FilterRegistrationBean
-
FilterRegistrationBean<SAPServiceFilter> filterRegBean = new FilterRegistrationBean<>();
filterRegBean.setFilter(new SAPServiceFilter());
推荐答案
您可以使用构造函数注入。假设您的过滤器注册bean存在于一个组件中,并且可以访问您可以在那里自动装配它的服务并使用构造函数传递它
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
@Autowired
AuthRequestService authRequestService;
[...]
FilterRegistrationBean<SAPServiceFilter> filterRegBean = new FilterRegistrationBean<>();
filterRegBean.setFilter(new SAPServiceFilter(authRequestService));
这篇关于Spring boot-将服务注入doFiler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!