版权声明:本文为hoaven原创文章,未经博主允许不得转载。 https://blog.csdn.net/hehuanchun0311/article/details/80513558
1、问题描述
SpringBoot
中filter注入bean
时注入失败,bean
一直为空。
@Slf4j
@Component
public class RestAuthFilter extends FormAuthenticationFilter {
//实际注入为null
@Autowired
MobileDeviceService mobileDeviceService;
@Autowired
UserService userService;
...
}
2、问题探究
其实
Spring
中,web应用启动的顺序是:listener->filter->servlet
,先初始化listener
,然后再来就filter
的初始化,再接着才到我们的dispathServlet
的初始化,因此,当我们需要在filter
里注入一个注解的bean
时,就会注入失败,因为filter
初始化时,注解的bean
还没初始化,没法注入。
3、解决方法
/**
* 解决Filter中注入Bean失败
* Created by hoaven on 2018/5/30.
*/
@Slf4j
@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
if (SpringUtils.applicationContext == null) {
SpringUtils.applicationContext = applicationContext;
}
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//根据name
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
//根据类型
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
使用:
if (mobileDeviceService == null) {
mobileDeviceService = (MobileDeviceService) SpringUtils.getBean("mobileDeviceServiceImpl");
}
if (userService == null) {
userService = (UserService) SpringUtils.getBean("userServiceImpl");
}