Problem Description
Spring
In Filter注入Bean
when injected failure, Bean
it has been empty.
@Slf4j
@Component
public class RestAuthFilter extends FormAuthenticationFilter {
//实际注入为null
@Autowired
MobileDeviceService mobileDeviceService;
@Autowired
UserService userService;
...
}
problem analysis
Spring, the order of the web application is launched: listener-> filter-> servlet.
Initialized listener, and then come back to filter initialization, then and then only to the initialization of our dispathServlet,
Therefore, when we need to inject a note of bean in the filter, the injection will fail,
Because when the filter is initialized, not annotated bean initialization, not injected.
solution
Method a: Tools manual injection
Spring injection tools Reference: https://shentuzhigang.blog.csdn.net/article/details/104735859
Manual injection Optimizer class: Method two
https://www.liangzl.com/get-article-detail-158316.html
Method three: tectonic loading
1, since the configuration section defines SecurityMetadataSource using loading configuration
<beans:bean id="mySecurityMetadataSource" class="app_security.MyInvocationSecurityMetadataSource">
<beans:constructor-arg><beans:ref bean="resourceDao"/></beans:constructor-arg>
</beans:bean>
<beans:bean id="resourceDao" class="com.ipi.tyr.module.resourceModule.dao.impl.ResourceDaoImpl"></beans:bean>
2, in the custom class securityMetadataSource
private ResourceDao resourceDao;
public MyInvocationSecurityMetadataSource(ResourceDao resourceDao) {
this.resourceDao = resourceDao;
loadResourceDefine();
}
Reference article
https://blog.csdn.net/hehuanchun0311/article/details/80513558
https://www.iteye.com/blog/awaitdeng-1040020
https://www.cnblogs.com/happyflyingpig/p/7998449.html