问题描述
Spring
中Filter注入Bean
时注入失败,Bean
一直为空。
@Slf4j
@Component
public class RestAuthFilter extends FormAuthenticationFilter {
//实际注入为null
@Autowired
MobileDeviceService mobileDeviceService;
@Autowired
UserService userService;
...
}
问题分析
Spring中,web应用启动的顺序是:listener->filter->servlet.
先初始化listener,然后再来就filter的初始化,再接着才到我们的dispathServlet的初始化,
因此,当我们需要在filter里注入一个注解的bean时,就会注入失败,
因为filter初始化时,注解的bean还没初始化,没法注入。
解决方案
方法一:工具类手动注入
Spring注入工具类参考:https://shentuzhigang.blog.csdn.net/article/details/104735859
方法二:工具类手动注入优化
https://www.liangzl.com/get-article-detail-158316.html
方法三:构造加载
1、自定义的SecurityMetadataSource配置部分,使用构造加载
<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、在自定义的securityMetadataSource类
private ResourceDao resourceDao;
public MyInvocationSecurityMetadataSource(ResourceDao resourceDao) {
this.resourceDao = resourceDao;
loadResourceDefine();
}
参考文章
https://blog.csdn.net/hehuanchun0311/article/details/80513558
https://www.iteye.com/blog/awaitdeng-1040020
https://www.cnblogs.com/happyflyingpig/p/7998449.html