filter过滤器注入bean实例时注入失败null

版权声明:本文为hoaven原创文章,未经博主允许不得转载。 https://blog.csdn.net/hehuanchun0311/article/details/80513558

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

猜你喜欢

转载自blog.csdn.net/hehuanchun0311/article/details/80513558