filter過濾器注入bean例項時注入失敗null
阿新 • • 發佈:2018-11-21
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");
}