Spring Boot - ApplicationContextAware

  • 当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean。
  • 换句话说,就是这个类可以直接获取spring配置文件中,所有有引用到的bean对象。
  • applicationContext可以拿到所有创建的Bean对象,从而做一些操作。比如已知某个Bean名称查询Class,通过上下文拿到所有加了某注解的类
import com.evget.exception.BaseException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ContextUtil implements ApplicationContextAware {
  
    // 定义一个上下文context;
    // 通过context.getBean(name); 获取对象
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        this.context = context;
    }

    public static <T> T get(Class<T> c) {
        try {
            return context.getBean(c);
        } catch (Exception e1) {
            try {
                return c.newInstance();
            } catch (Exception e2) {
                throw new BaseException(e2.toString());
            }
        }
    }
    
    public static Object service(String name) {
        return context.getBean(name);
    }
}