1. 程式人生 > >filter過濾器注入bean例項時注入失敗null

filter過濾器注入bean例項時注入失敗null

1、問題描述

SpringBootfilter注入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");
}