springMvc shiro整合,shiro的Realm不能自动注入service问题

本文属于原创,如有问题,可留言探讨
不能注入service的问题在网上找了很多资料,但是都是没有解决我的问题

springMvc shiro整合,shiro的Realm不能自动注入service问题_第1张图片
原因分析:spring 加载时候,注入的 bean 的顺序是 先是 Lisener 然后是 Filter 最后是 Servlet
因此如果在过滤器或者监听器里面注入 service 等会是空,因为在过滤器或者监听器加载的时候
因此为了解决这个问题,现在要进行手动注入

下面代码是工具类,手动注入service,到此问题解决

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * spring加载时候,注入的bean 的顺序是 先是Lisener 然后是 Filter 最后是 Servlet
 * 因此如果在过滤器或者监听器里面注入service等会是空,因为在过滤器或者监听器加载的时候
 * Servletservice等还没有加载,因此是空的,所以就手动注入
 *
 * Created by zhong.h on 2018/6/13/013.
 */
@Component
public class SpringBeanFactoryUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        if (SpringBeanFactoryUtils.applicationContext == null) {
            SpringBeanFactoryUtils.applicationContext = applicationContext;
        }

    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //根据名称(@Resource 注解)
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    //根据类型(@Autowired    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);
    }
}

你可能感兴趣的:(springMvc shiro整合,shiro的Realm不能自动注入service问题)