通用获取SpringBean的工具,可在Spring无法注入的场景下使用Spring相关Bean

@Component
public final class SpringUtil implements ApplicationContextAware {  
    private static ApplicationContext applicationContext = null;  
  
    @Override  
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
        if (SpringUtil.applicationContext == null) {  
            SpringUtil.applicationContext = applicationContext;  
        }  
    }  
  
    public static ApplicationContext getApplicationContext() {  
        return applicationContext;  
    }  
  
    public static Object getBean(String name) {  
        return getApplicationContext().getBean(name);  
    }  
}  

可直接通过SpringUtil.getBean([beanName]);

你可能感兴趣的:(通用获取SpringBean的工具,可在Spring无法注入的场景下使用Spring相关Bean)