0
点赞
收藏
分享

微信扫一扫

Spring 强行获取bean

ixiaoyang8 2022-02-22 阅读 67
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
 * 获取bean
 */
@Component
public class SpringBeanFactoryUtils implements ApplicationContextAware {
    private static ApplicationContext context = null;

    public static <T> T getBean(Class<T> type) {
        return context.getBean(type);
    }

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

使用方法

  @Autowired
    RedisUtils redisUtils;



    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        String token = getRequestToken((HttpServletRequest) request);
        String url = ((HttpServletRequest) request).getServletPath();
        //如果为登录,就放行
        if ("/admin/user-info/login".equals(url)) {
            return true;
        }
        try {
            if(redisUtils == null){
                redisUtils = SpringBeanFactoryUtils.getBean(RedisUtils.class);
            }
...................................
举报

相关推荐

0 条评论