Spring Boot 在非spring控制的组件获取bean

Posted by 浮生 on 03-31,2020
/**
 * @ClassName SpringUtil
 * @Description Spring 工具类
 * @Author WFS
 * @Date 2019/4/3 11:03
 **/

@Component
public class SpringUtil implements ApplicationContextAware {

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

    private static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

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

}

需要注意几点

  1. SpringUtil需要被Spring Boot 扫描到
  2. 使用的时机需要在spring容器加载完所有Bean以后