SpringContextUtils 工具类 获取 某个类的实例

因为XX类 没有被声明为@Bean, 那么换句话说 XX类 就没有被Spring管理起来,那么也就无法在里面注入OO类了。 
但是在业务上XX类 里面又必须使用OO类,怎么办呢? 就借助SpringContextUtils 这个工具类,来获取OO类的实例。 
这里提供工具类,下个步骤讲解如何使用这个工具类。

package com.example.springboot.shiro.common.utils;

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


@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext context;

    public void setApplicationContext(ApplicationContext context)
            throws BeansException {
        SpringContextUtil.context = context;
    }

    public static ApplicationContext getContext(){
        return context;
    }
}

 

posted @ 2018-08-13 17:14  王某人i  阅读(790)  评论(0编辑  收藏  举报